Kaku
Kaku

Reputation: 21

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 ?

Upvotes: 3

Views: 3528

Answers (1)

Leo Gomes
Leo Gomes

Reputation: 1153

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.

Upvotes: 4

Related Questions