服务端启动正常,客户端连接时报如下错误:
Exception in thread "main" io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: /127.0.0.1:6668
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
at io.netty.channel.socket.nio.NioSocketChannel.doFinishConnect(NioSocketChannel.java:325)
at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:340)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:633)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:580)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:497)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:459)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:886)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused: no further information
... 11 more
分析:
1. 从报错信息显示时服务器无法连接,采用分段排除法,用另外一个正常的服务端代码和两外一个正常的客户端分别进行连接,结果换一个正常的服务端后该客户端可以正常连接,则问题出现在服务端一侧;
2. 分析比对代码,发现问题出现在监听channel并closeChannel的时候没有加sync, 此时直接closeChannel(),并且执行finally在中的线程池关闭操作
public static void main(String[] args) throws InterruptedException {
// 创建BossGrouper和WorkerGroup
// bossGroup只处理连接请求
// workGroup处理真正的业务逻辑
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
try {
// 创建服务器端的启动对象,配置启动参数
ServerBootstrap bootstrap = new ServerBootstrap();
// 使用链式编程进行设置
bootstrap.group(bossGroup, workerGroup) // 设置2个线程组
.channel(NioServerSocketChannel.class) // 使用NioServerSocketChannel作为服务器的通道实现
.option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列等待连接的个数
.childOption(ChannelOption.SO_KEEPALIVE, true) // 保持活动连接状态
.childHandler(new ChannelInitializer<SocketChannel>() {
// 向pipline设置处理器
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
System.out.println("客户socketChannel hashCode=" + socketChannel.hashCode());
// 将socketChannel放到集合中管理,当有消息推送式加入到NioEventLoop对应的taskQueues中执行
socketChannel.pipeline().addLast(new NettyServerHandler());
}
}); // 给eventLoop对应的管道
System.out.println("... Server is ready...");
// 绑定端口并且同步,生成一个channelFuture对象
ChannelFuture cf = bootstrap.bind(6668).sync();
cf.addListener((future) -> {
if (cf.isSuccess()) {
System.out.println("监听端口6668成功");
} else {
System.out.println("监听端口6668失败");
}
});
// 对关闭通道进行监听
cf.channel().closeFuture().sync();
// cf.channel().closeFuture();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
参考代码: