Choice of transports for JSON over TCP

前端 未结 5 1198
小鲜肉
小鲜肉 2020-12-24 03:16

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

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 03:59

    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:

    1. Read the first four bytes of data and figure out the exact amount of bytes you need to read the whole message.
    2. Read the rest of the message and deserialize it as a JSON

    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);
        }
    

提交回复
热议问题