[英]Netty: Why different packets are connected together as an request in the server?
Here's the only handler in the Netty client, I sent 3 packets to the server. 这是Netty客户端中唯一的处理程序,我向服务器发送了3个数据包。
@Sharable
public class ClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.copiedBuffer("1", CharsetUtil.UTF_8));
ctx.writeAndFlush(Unpooled.copiedBuffer("2", CharsetUtil.UTF_8));
ctx.writeAndFlush(Unpooled.copiedBuffer("3", CharsetUtil.UTF_8))
.addListener(ChannelFutureListener.CLOSE);
}
}
In the server handler, I just print it, expected 3 times with separate 1
, 2
and 3
, but 123
actually. 在服务器处理,我只是单独打印出来,预计3次
1
, 2
和3
,但123
实际上。 What happened? 发生了什么? Isn't them different packets?
它们不是不同的包装吗?
@Sharable
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) {
System.out.println(in.toString(CharsetUtil.UTF_8));
}
}
TCP/IP protocol (that you are probably using in your server) is stream-based. TCP / IP协议(您可能正在服务器中使用)是基于流的。 That means the buffer of a stream-based transport is not a queue of packets but a queue of bytes.
这意味着基于流的传输的缓冲区不是数据包队列,而是字节队列。 So it is up to OS how to send your data - as separate packets or as 1 packet with all your data combined.
因此,取决于操作系统如何发送数据-作为单独的数据包还是合并了所有数据的1个数据包。
You have 3 options either add some separator or send fixed length packets or attach packet size to message. 您有3个选项,或者添加一些分隔符,或者发送固定长度的数据包,或者将数据包的大小附加到消息中。
Here is more details in netty documentation. 这是 Netty文档中的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.