开发者

Socket.BeginReceive callback - message separator

When the callback assigned by Socket.BeginReceive() gets some bytes, what is the best way to know I have the whole message? Should I have the first 4 bytes of each message I send hold the length of the message?

I am sending an XML file in each message so t开发者_JAVA百科here is no unique character I can use as a message separator.


Follow the specification for the protocol you are using. If it's an original protocol, write a specification. It's a bit of extra work, but it's well worth it.

In that specification, you can specify a message length. You can also prohibit a particular byte (you could user zero) in the payload and use that as a message separator. Since you're using XML, you could simply define a tag that indicates a message -- the close of that tag would indicate a complete message.

It's up to you. But spend the time to specify your protocol in detail. I promise you it will pay off.


I would use a header containing two integers (4 bytes each). The first one would indicate protocol version and the second one would indicate message length. The good thing with using a header length instead of a delimiter is that you can allocate a buffer for the entire message before you start parsing it.

Using a version integer as the first header let's you change the rest of the headers, and the body, in any newer version of the protocol.

Update in reply to the comment

There is a difference between version number in the header and the one in the actual message. The message version is for the document, but the header version is for the protocol itself. By using a protocol version you could switch message transport from XML to Protobuf or something else for the message. You could also add a header identifying the target of the actual message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜