如何使用 Netty 4.0.x 检测新的传入连接? 这是一个简单服务器的代码:
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
System.out.println("Init channel");
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
System.out.println("Channel registered");
}
@Override
public void channelActive(final ChannelHandlerContext ctx) {
System.out.println("Channel active");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
System.out.println("Channel read");
ctx.writeAndFlush((ByteBuf) msg);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.out.println("Channel exception caught");
cause.printStackTrace();
ctx.close();
}
});
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f;
try {
f = b.bind("127.0.0.1", 8080).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
问题是我无法检测到连接建立的时刻。所有 System.out.printlns 仅在客户端向服务器发送一些信息后调用。这意味着在客户端向服务器发送一些数据之前,服务器不能向客户端发送任何数据。
我的期望:
- 服务器启动
- 客户端启动
- 客户连接
- {{ 初始化 channel }}
- {{ 已注册 channel }}
- {{ channel 活跃}}
- //可能从服务器向客户端发送一些数据
- 客户端发送一些数据
- {{ channel 阅读 }}
我得到的:
- 服务器启动
- 客户端启动
- 客户连接
- //无法向客户端发送任何数据
- 客户端发送一些数据
- {{ 初始化 channel }}
- {{ 已注册 channel }}
- {{ channel 活跃}}
- {{ channel 阅读 }}
有什么方法可以实现这种行为吗?
最佳答案
当客户端连接到服务器时,你可以发送一些数据,所以你可以在 channelRegistered 或 channelActive 方法中使用 ctx.writeAndFlush(msg) 。 如果您的客户端没有收到任何数据,您应该确保 Encode 的类型是正确的。
关于events - 如何使用 Netty 4.0.x 检测新的传入连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079747/