如何使用 Netty 4.0 在连接变为非活动状态后重新连接



我有scanerio,一旦连接由于使用netty 4.0的任何原因变得不活动,我必须重新连接到服务器。以下是一次连接到服务器的代码。

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();
        }

你应该将一个 ChannelFutureListener 添加到 connect(...) 返回的 ChannelFuture 中,并检查未来是否失败。如果失败,您可以根据需要尝试重新连接。

相关内容

最新更新