处理Netty中的分散性 [英] Dealing with fragmentation in Netty

查看:88
本文介绍了处理Netty中的分散性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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:

表示ID号的前4个字节 剩余的字节是一个字符串

first 4 bytes to represent an id number the remaining bytes is a String

在我所看到的示例中,消息的大小是固定的,但是String内容可以是任何大小,并且需要确保在服务器接收到消息时不将其分割.我将如何在Netty中实现这一目标?

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?

谢谢.

推荐答案

您如何确定消息的结尾?零吗我会检查Netty重播解码器:

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

它使您的事情变得容易.继续阅读,直到找到零为止.如果在达到零之前用完字节,则会抛出异常以退出解码方法.当有更多字节可用时,将使用现有字节和新字节合并在一个ChannelBuffer中再次调用解码方法.

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.

可以重复此循环,直到将整个消息保存在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.

这篇关于处理Netty中的分散性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆