【问题标题】:How to reconnect to a server after the server stopped serving request in Netty IO服务器停止在 Netty IO 中服务请求后如何重新连接到服务器
【发布时间】:2018-11-20 08:08:07
【问题描述】:

每当服务器重新启动或现有连接中断时,我的 netty IO 客户端应该继续尝试连接到服务器。为了实现这一点,每当调用我的 ChannelInboundHandlerAdapter 的 ChannelInActive 回调方法时,我的客户端都会创建一个新线程来建立新连接。但是我的客户端在建立新连接时抛出了以下错误。

线程“主”io.netty.channel.AbstractChannel$AnnotatedConnectException 中的异常:连接被拒绝:没有更多信息:/127.0.0.1:8888 在 sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) 在 sun.nio.ch.SocketChannelImpl.finishConnect(未知来源) 在 io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325) 在 io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340) 在 io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633) 在 io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized (NioEventLoop.java:580) 在 io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497) 在 io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459) 在 io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886) 在 io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) 在 java.lang.Thread.run(未知来源) 引起:java.net.ConnectException:连接被拒绝:没有更多信息 ... 11 更多

下面几行是我的连接线程的运行部分。

EventLoopGroup group = new NioEventLoopGroup();
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group);
bootstrap.channel(NioSocketChannel.class).handler(new 
ChannelInitializer<SocketChannel>() {

        protected void initChannel(SocketChannel socketChannel) throws 
Exception {
            socketChannel.pipeline().addLast(new 
LengthFieldBasedFrameDecoder(64 * 1024, 0, 2));
            socketChannel.pipeline().addLast(ClientHandler);
        }

    });
    bootstrap.option(ChannelOption.SO_REUSEADDR,true);
    ChannelFuture channelFuture=null;
try 
{
    channelFuture = bootstrap.connect(new InetSocketAddress(IP, 
port)).sync();      
    channelFuture.awaitUninterruptibly();
    channelFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture channelFuture)
         {
        try
        {
            if (channelFuture.isSuccess()) {
            if(connectfuture!=null) connectfuture.cancel(true);log.debug("Cancelled connection thread scheduler");

        } else {
            channelFuture.cause().printStackTrace();
        connectfuture=channelFuture.channel().eventLoop().scheduleAtFixedRate(new ClientConnectorThread(ClientHandler,IP,port) , 5,30, TimeUnit.SECONDS);
        }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        }
        } );

}

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

【问题讨论】:

    标签: java server io client netty


    【解决方案1】:

    当我要实现重连逻辑的时候,我是这样做的

    为管道添加两个处理程序以捕获空闲状态

    pipeline.addLast(new ReadTimeoutHandler(readTimeout, TimeUnit.SECONDS));
    pipeline.addLast("ReconnectionHandler", new ReconnectionHandler());
    

    ReconnectionHandler捕获ReadTimeoutHandler触发的用户事件,断开通道并尝试重新连接

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                ctx.close();
            }
        } else {
            ctx.fireUserEventTriggered(evt);
        }
    }
    
    public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {
        final EventLoopGroup eventLoopGroup = ctx.channel().eventLoop().parent();
        eventLoopGroup.schedule(() -> {
            bootstrap.connect()
        }, reconnectDelay, TimeUnit.SECONDS);
        ctx.fireChannelUnregistered();
    }
    

    【讨论】:

    • 非常感谢您的回复!正如你所提到的,我有一个处理程序(SimpleChannelInboundHandler)添加到我的管道中,它有一个名为“channelInactive”的回调方法。因此,一旦服务器关闭连接,就会正确调用此方法,但是当我尝试使用 bootstrap.connect(new InetSocketAddress(IP,Port)) 方法创建连接时,会出现上述错误行。
    • 如果是这种情况,您需要首先确定服务器是否正在侦听端口。当所述异常触发时 Telnet 到端口。如果您无法远程登录,则故障出在服务器而不是客户端。
    猜你喜欢
    • 2019-09-25
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2019-11-30
    • 2012-12-16
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多