for (int i = 1; i <= 100; i++) {
ctx.writeAndFlush(Unpooled.copiedBuffer(Integer.toString(i).getBytes(Charsets.US_ASCII)));
}
ctx.writeAndFlush(Unpooled.copiedBuffer("ABCD".getBytes(Charsets.US_ASCII))).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
ctx.channel().close();
}
});
我把这个写在我的netty服务器处理程序的channelRead()方法中,一旦服务器收到请求,它就会将“12345...100ABCD”返回给客户端。
据我所知,客户端从netty服务器接收到的消息的顺序始终是“12345...100ABCD”。
我不知道这只是偶然吗?也许有时它会是“32451...ABCD100”(超出服务器写入顺序)?
服务器是否有可能执行
clientChannel.writeAndFlush(msg1);
clientChannel.writeAndFlush(msg2);
clientChannel.writeAndFlush(msg3);
但是客户端收到了msg2-msg1-msg3或msg3-msg1-msg2,但没有收到写入命令msg1-msg2-msg3
netty项目的代理样本中,https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/proxy
HexDumpProxyBackendHandler 写道:
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ctx.channel().read();
} else {
future.channel().close();
}
}
});
}
它确保仅当 wirteAndFlush() 操作完成时才会触发下一个channelRead()(即channelRead()中的inboundChannel.writeAndFlush(msg))。
那么在监听器中写入 ctx.channel().read() 并在 future.isSuccess() 时执行它的目的是什么?不是为了确保写入客户端的消息按正确的顺序接收吗?
如果我把它改成
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
inboundChannel.writeAndFlush(msg);
ctx.channel().read();
}
这会导致一些问题吗?
最佳答案
不,这是不可能的。 TCP 确保了这一点。
关于java - 客户端收到的消息是否有可能在 netty 服务器写入时乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320653/