为什么客户端重新连接会导致与Netty的双重连接

时间:2018-11-22 08:33:59

标签: java netty

使用Netty关闭连接后,客户端将重新连接到服务器。但是,每当连接断开时,客户端将使用两个线程重新连接。重新连接导致双重连接。我该如何解决这个问题?

public class ImConnection {
    private static Logger logger = LoggerFactory.getLogger(ImConnection.class);
    private static Bootstrap b;
    private Channel channel;

    static {
        b = new Bootstrap();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ConnectionInitializer());
    }

    public Channel connect() {
        doConnect(PropertyConstant.cfgcServerIP, PropertyConstant.cfgcServerPort);
        return this.channel;
    }
    private void doConnect(String host, int port) {
        try {
            ChannelFuture f = b.connect(host, port);
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        final EventLoop loop = future.channel().eventLoop();
                        loop.schedule(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    connect(); // reconnect if fail
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, 1L, TimeUnit.SECONDS);
                    } else {
                        logger.info("connected");
                    }
            }});
            channel = f.channel();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

处理程序初始化程序

public class ConnectionInitializer extends ChannelInitializer<Channel> {

    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new ConnectionHandler());
    }
}

在连接断开时重新连接的处理程序

public class ConnectionHandler extends ChannelInboundHandlerAdapter {
    private ImConnection imConnection = new ImConnection();

    // get executed when connection drops
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.err.println("connection lost");
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(new Runnable() {
            @Override
            public void run() {
                imConnection.connect();
            }
        }, 1L, TimeUnit.SECONDS);
        super.channelInactive(ctx);
    }
}

0 个答案:

没有答案