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?