【发布时间】: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