7-11节 Netty服务器报错,客户端连接后Netty服务器报错 请问下怎么解决啊
来源:7-11 基于Netty搭建IM系统基本骨架和编解码器

HERTION
2023-11-05
客户端代码:
package cn.alex;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class test {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(9092));
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("connected");
}
}
}
服务端代码
package cn.alex;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyIMServerApplication {
public void startServer() throws InterruptedException {
// 处理 accept事件
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
// 处理读写事件
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup);
bootstrap.channel(NioServerSocketChannel.class);
bootstrap.childHandler(new ChannelInitializer<>() {
@Override
protected void initChannel(Channel channel) throws Exception {
System.out.println("init " + channel.id());
}
});
Runtime.getRuntime().addShutdownHook(new Thread(()->{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}));
ChannelFuture channelFuture = bootstrap.bind(9092).sync();
System.out.println("服务启动成功,监听端口为 9092");
// 这里会阻塞掉主线程,实现服务长期开启
channelFuture.channel().closeFuture().sync();
}
public static void main(String[] args) throws InterruptedException {
NettyIMServerApplication application = new NettyIMServerApplication();
application.startServer();
}
}
谢谢老师
写回答
2回答
-
我拷贝了一份你的代码,发现运行是正常的。但是从你的日志来看,像是一开始连接正常,但是后续出现了网络波动,导致连接断开了,要不从本地环境开始排查看看?
012023-11-06 -
慕田峪604633
2024-02-24
我也遇到这个问题,我这边是把客户端的睡眠等待时间调整到和老师一样,就正常了。老师能解答下原理 吗
022024-02-25
相似问题