java - 客户端收到的消息是否有可能在 netty 服务器写入时乱序

标签 java netty

    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/

相关文章:

java - Netty IO 无所事事的编解码器?

java - 使用 byte[] 数组通过 ByteBuf 读写字符串

java - ObjectEncoderOutputStream 可能出现内存不足异常吗?

java - 检查 Netty 服务器是否启动时 sleep 的替代方案?

java - 如何获取服务器名称、端口和上下文

java - hibernate 拦截器后保存?

java - 是否存在美观、用户友好的 Java 小程序?

Java BlockingQueue take() 与 poll()

java - Jboss Netty - 如何使用 3 个工作线程服务 2 个连接

java - 如何找到要在Excel单元格中写入的列名