Netty 客户端断线重连

坚强是说给别人听的谎言 提交于 2020-11-14 10:19:59

client 关闭后会执行 finally 代码块,可以在这里可以进行重连操作

public class NettyClient implements Runnable {

    private final String host;
    private final int port;
    private final int reconnectSleepSeconds;

    public NettyClient(String host, int port, int reconnectSleepSeconds){
        this.host = host;
        this.port = port;
        this.reconnectSleepSeconds = reconnectSleepSeconds;
    }

    @Override
    public void run() {
        connect();
    }

    private void connect(){
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    // TODO: 添加 Handler
                }
            });

            ChannelFuture f = b.connect(host, port).sync();

            f.channel().closeFuture().sync();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();

            try {
                TimeUnit.SECONDS.sleep(reconnectSleepSeconds);

                connect(); // 断线重连

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

参考:微言netty:不在浮沙筑高台

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!