简体   繁体   中英

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.

@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. 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. 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.

You have 3 options either add some separator or send fixed length packets or attach packet size to message.

Here is more details in netty documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM