umair yasin
umair yasin

Reputation: 159

how to reconnect after the connection becomes inactive using netty 4.0

i have scanerio in which i have to reconnect to the server once the connection becomes inactive due to any reason using netty 4.0.Code should try to reconnect until it is connected successfully..Following is the code to connect to server once.

Bootstrap b;
b.group(group);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000);
//        b.option(ChannelOption., 10000);
        b.handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
               ch.pipeline().addLast("frameDecoder", new DelimiterBasedFrameDecoder(bufferSize,bt));
               ch.pipeline().addLast("ByteDecoder", new ByteArrayDecoder());                    
               ch.pipeline().addLast("frameEncoder", new ByteArrayEncoder());
               ch.pipeline().addLast (new TimeClientHandler (c));
             }
         });
        System.out.println("Connecting Server");
        this.host = host;
        this.port = port;
        try {
            f = b.connect(host, port).sync();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Upvotes: 2

Views: 2469

Answers (1)

Norman Maurer
Norman Maurer

Reputation: 23557

You should add a ChannelFutureListener to the ChannelFuture returned by connect(...) and check if the future is failed or not. If it is failed you can try to reconnect if needed.

Upvotes: 3

Related Questions