0

I'm implementing a protocol by using SSLStream class. I started with reading message like this (receiving ASCII characters in a message):

byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
     // Read the client's test message.
     bytes = sslStream.Read(buffer, 0, buffer.Length);

     // Use Decoder class to convert from bytes to UTF8 
     // in case a character spans two buffers.
     Decoder decoder = Encoding.UTF8.GetDecoder();
     char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
     decoder.GetChars(buffer, 0, bytes, chars,0);
     messageData.Append (chars);
     // Check for EOF or an empty message. 
     if (messageData.ToString().IndexOf("<EOF>") != -1)
     {
         break;
     }
} while (bytes !=0); 

However, now protocol changed, and I don't need to search for for end of message, but I need to first read a message length first (in number of characters) and then to read message with the received length. How can I do this?

Milan M.
  • 959
  • 3
  • 12
  • 27

1 Answers1

0

You have to use TLV (type Length Value) format, or just LV. Use the first two Bytes for the length, this gives size for a short int, I suppose this is enough for your exercise but you can use more bytes if necessary. So always read 2 Bytes. After you receive the 2 Bytes, you get the number (say it was sent in binary format) and the you read the specified number of octets/Bytes or characters. Pay attention to endianship, surely little endian. In this link you can see in my response how I do it for Java: How to read all of Inputstream in Server Socket JAVA

Community
  • 1
  • 1
rodolk
  • 5,606
  • 3
  • 28
  • 34