码迷,mamicode.com
首页 > Web开发 > 详细

Netty 客户端断线重连

时间:2019-04-29 12:54:50      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:eps   catch   string   .sh   pre   trace   代码   run   group   

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:不在浮沙筑高台

Netty 客户端断线重连

标签:eps   catch   string   .sh   pre   trace   代码   run   group   

原文地址:https://www.cnblogs.com/victorbu/p/10789527.html

(1)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!