67 private final Multiset<Connection> connections = ConcurrentHashMultiset.create();
70 public void channelActive(ChannelHandlerContext ctx)
throws Exception {
71 Connection connection = getConenction(ctx);
72 connection.setCanConnect(
true);
76 public void channelRegistered(ChannelHandlerContext ctx)
throws Exception {
77 Connection connection = getConenction(ctx);
80 if (!connection.canConnect()) {
88 if (connection.getHost().equalsIgnoreCase(
"127.0.0.1")) {
93 connection.addConnection();
106 connections.add(connection);
107 connection.setCanConnect(
false);
113 ctx.fireChannelRegistered();
117 public void channelUnregistered(ChannelHandlerContext ctx)
throws Exception {
118 Connection connection = getConenction(ctx);
124 if (connection.getHost().equalsIgnoreCase(
"127.0.0.1")) {
128 connection.removeConnection();
131 if (connection.getConnections() == 0) {
132 connections.remove(connection);
139 ctx.fireChannelUnregistered();
150 private void disconnect(ChannelHandlerContext ctx,
LoginResponse response) {
152 ByteBuf initialMessage = ctx.alloc().buffer(8).writeLong(0);
154 ctx.write(initialMessage, ctx.voidPromise());
155 ctx.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE);
166 private Connection getConenction(ChannelHandlerContext ctx) {
167 String host = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
168 return connections.stream().filter(conn -> conn.getHost().equalsIgnoreCase(host)).findFirst().orElse(
new Connection(host));
176 private static class Connection {
179 private final AtomicBoolean canConnect =
new AtomicBoolean(
true);
182 private final String host;
185 private int connections;
193 public Connection(String host) {
202 public String getHost() {
211 public int getConnections() {
220 public boolean canConnect() {
221 return canConnect.get();
225 public void addConnection() {
230 public void removeConnection() {
234 public void setCanConnect(
boolean val) {
235 canConnect.compareAndSet(!val, val);
239 public int hashCode() {
240 return Objects.hash(host);
244 public boolean equals(Object obj) {
245 if (obj instanceof Connection) {
246 Connection other = (Connection) obj;
247 return host.equalsIgnoreCase(other.getHost());
253 public String toString() {
254 return String.format(
"Connection[host=%s, connections=%s, elapsed=%s]", host, connections, canConnect);