I\'m writing a simple streaming JSON service. It consists of JSON messages, sent intermittently, for a long period of time (weeks or months).
What is the best pract
The first of four bytes of the message can be an 32-bit integer indicating size (in bytes) of the message. Then the receiver should follow these steps:
Sender code in C#:
public void WriteMessage(Packet packet) {
// Convert the object to JSON
byte[] message = Encoding.UTF8.GetBytes(packet.Serialize());
// Serialize the number of characters
byte[] messageLength = BitConverter.GetBytes(message.Length);
// Build the full message that will hold both the size of the message and the message itself
byte[] buffer = new byte[sizeof(int) + message.Length];
Array.Clear(message, 0, message.Length);
// Print the size into the buffer
for (int i = 0; i < sizeof(int); i++)
{
buffer[i] = messageLength[i];
}
// Print the message into the buffer
for (int i = 0; i < message.Length; i++)
{
buffer[i + sizeof(int)] = message[i];
}
// Send it
stream.Write(buffer, 0, buffer.Length);
}