Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
afuzzyllama Avatar asked Dec 20 '12 14:12

afuzzyllama


1 Answers

There are different approaches on this. One option would be sending the length of the class name and possible of the whole packet first (e.g. 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.

like image 97
ThiefMaster Avatar answered Sep 28 '22 02:09

ThiefMaster