处理 Netty 中的碎片
我正在使用 Netty 设计一个用于客户端/服务器通信的二进制协议,发送的字节数不是固定数量,可以是任意大小。
客户端发送的内容如下:
前 4 个字节表示 id 号 剩余的字节是一个字符串
在我看到的示例中,消息的大小是固定的,但字符串内容可以是任何大小,并且需要确保服务器接收时它不会分段。我如何在 Netty 中实现这一目标?
提前致谢。
I am designing a binary protocol for client/server communication using Netty and the number of bytes sent is not fixed amount and can be arbitrary size.
The client is sending something like this:
first 4 bytes to represent an id number
the remaining bytes is a String
In the example I have seen, the message has been a fixed size but the String content could be any size and need to ensure it is not fragmented when received by the server. How would I achieve this in Netty?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你如何确定消息的结束?零?我会检查 Netty 重放解码器:
http://docs.jboss.org/netty/3.2/api/org/jboss/netty/handler/codec/replay/ReplayingDecoder.html
它让你的事情变得简单。继续阅读,直到找到零。如果在到达零之前用完字节,则会抛出异常以退出解码方法。当有更多字节可用时,将再次调用解码方法,将现有字节和新字节组合在一个 ChannelBuffer 中。
这个循环可以重复,直到您在 ChannelBuffer 中拥有整个消息……然后您可以将其传递到下一层进行处理。
如果可以更改您的协议,我会添加一个长度,因为能够读取长度比检查每个字节是否为零要有效得多。
How are you determining the end of message? A zero? I would check out the Netty replaying decoder:
http://docs.jboss.org/netty/3.2/api/org/jboss/netty/handler/codec/replay/ReplayingDecoder.html
It makes things easy for you. Just keep reading until you find a zero. If you run out of bytes before you reach the zero an exception will be thrown to exit the decode method. When more bytes are available, the decode method will be called again with the existing bytes and the new bytes combined in one ChannelBuffer.
This cycle can repeat until you have the whole message in the ChannelBuffer...which then you can pass up to the next layer for processing.
If it was possible to change your protocol I would add a length as being able to read to length is far more efficient than checking every byte for a zero.
或者,如果它是基于行的,您可以使用 DelimiterBasedFrameDecoder 来完成这项工作。
看:
http://netty.io/docs /stable/api/org/jboss/netty/handler/codec/frame/DelimiterBasedFrameDecoder.html
Or if its line based you could just use the DelimiterBasedFrameDecoder for the job.
See:
http://netty.io/docs/stable/api/org/jboss/netty/handler/codec/frame/DelimiterBasedFrameDecoder.html