How to place a delimiter in a NetworkStream byte array?

I'm setting up a way to communicate between a server and a client. How I am working it at the moment, is that a stream's first byte will contain an indicator of what is coming and then looking up that request's class I can determine the length of the request:

stream.Read(message, 0, 1)

if(message == <byte representation of a known class>)
{
    stream.Read(message, 0, Class.RequestSize);
}

I'm curious how to handle the case of when the class size is not known, of if after reading a known request the data is corrupt.

I'm thinking that I can insert in some sort of delimiter into the stream, but since a byte can only be between 0-255, I'm not sure how to go about creating a unique delimiter. Do I want to place a pattern into the stream to represent the end of a message? How can I be sure that this pattern is unique enough to not be mistaken for actual data?


There are different approaches on this. One option would be sending the length of the class name and possible of the whole packet first (eg always the first byte). This way you can read just read that byte and then n bytes more to get the class name.

By this approach you don't end up reading a lot of stuff a malicious client sends you with the intent to DoS your application and you can quickly determine if you read enough to handle the packet or if it's not yet complete.


There are some low level bytes which are used especially as delimiters. Start of Text and End of Text have a (hex) value of 0x02 and 0x03 respectively. And you have Start of Heading coupled with End of Transmission, 0x01 and 0x04; you could use these.

链接地址: http://www.djcxy.com/p/11638.html

上一篇: Pydev和* .pyc文件

下一篇: 如何在NetworkStream字节数组中放置分隔符?