简体   繁体   中英

How to automatically connect to TCP server after disconnection in netty

I have a scenario where I am establishing TCP connection using netty NIO, suppose server went down than how can I automatically connect to server when it comes up again ? Or Is there any way to attach availability listener on server ?

You can have a DisconnectionHandler , as the first thing on your client pipeline, that reacts on channelInactive by immediately trying to reconnect or scheduling a reconnection task.

For example,

public class DisconnectionHandler extends ChannelInboundHandlerAdapter {

  @Override
  public void channelInactive(final ChannelHandlerContext ctx) throws Exception   {

    Channel channel = ctx.channel();
    
    /* If shutdown is on going, ignore */
    if (channel.eventLoop().isShuttingDown()) return;
    
    ReconnectionTask reconnect = new ReconnectionTask(channel);
    reconnect.run();
  }

}

The ReconnectionTask would be something like this:

public class ReconnectionTask implements Runnable, ChannelFutureListener {

    Channel previous;
    
    public ReconnectionTask(Channel c) {
        this.previous = c;
    }

    @Override
    public void run() {
         Bootstrap b = createBootstrap();
         b.remoteAddress(previous.remoteAddress())
          .connect()
          .addListener(this);
    }
    
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if (!future.isSuccess()) {
            // Will try to connect again in 100 ms.
            // Here you should probably use exponential backoff or some sort of randomization to define the retry period.
            previous.eventLoop()
                    .schedule(this, 100, MILLISECONDS); 
            return;
        }
        // Do something else when success if needed.
    }
}

Check here for an example of Exponential Backoff library .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM