The problem of unpacking and gluing netty packets: why does the server need data assembly when receiving tcp requests? Or what kind of data needs to be assembled?

there is a section of demo, in the user-guide of netty"s official website that is not very clear.
original text: ide-for-4.x.html-sharpwiki-h3-11" rel=" nofollow noreferrer "> netty4.x user Guide
Chinese: ide/Getting%20Started/Dealing%20with%20a%20Stream%20based%20Transport.html" rel= "nofollow noreferrer" > netty4.x user Guide
the data packet sent by the client, The server receives it in the form of a stream, so there needs to be a processing logic to parse the received stream into real packets sent by the client.

but I don"t feel the need to do so in my own demo. Because every time the client sends a string, the server can pass

String recMsg = byteBuf.toString(CharsetUtil.UTF_8);

parsed it completely and did not feel the need to do the operation mentioned in this article.

@Slf4j
public class EchoHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf buf = (ByteBuf) msg;
        String msgStr = buf.toString(CharsetUtil.UTF_8);
        log.info("receive message: {}", msgStr);
        
        ChannelFuture f = ctx.write(buf);
        f.addListener(new ChannelFutureListener() {
            
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                assert f == future;
                ctx.close();
            }
        });
    }
}
Is there any deviation in my understanding of

?
for example, the data written by the client is not only a string, but also mixed with other types of data, such as a long type?

ByteBuf time = ctx.alloc().buffer(4); // ChannelHandlerContext ctx
String dateNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
long curTime = System.currentTimeMillis();
time.writeBytes(dateNow.getBytes());
time.writeLong(curTime);
ctx.writeAndFlush(time);

if the client writes data like this line, and the server parses it according to the string type alone, it will indeed garble.
but will this really happen in reality? Can you give me two more specific examples?

Mar.28,2021

in fact, this is a typical problem of sticking and unpacking.

The reason for

is that TCP is streaming, just like the flow of water, there is no way to know where a complete message is cut off.

The longer the

message, the more likely it is to have such a problem.

what is mentioned in this article is to prevent packet unpacking according to byte length, and it is common to use delimiters, such as reading the specified delimiter, to obtain a complete message.

these Netty actually have built-in processors.


when sending data, for circulates the data several times more to see the effect of sticking packets.

Menu