Choice of transports for JSON over TCP

前端 未结 5 1205
小鲜肉
小鲜肉 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条回答
  •  Happy的楠姐
    2020-12-24 04:03

    my first two options would be:

    1. Do what early TCP protocols do: send one message (a JSON object in your case) and close the connection. The client detects it and reopens to get the next object.

      • pros: very easy to parse, no extra (content) bytes sent. any loss of data means losing just a single object. if you can stand that, there's no need to add retransmision to your app.
      • cons: if you send a (huge) lot of (very) small objects, the three-packet TCP handshake adds to latency.
    2. Do what chunked-mode HTTP does: first send the number of bytes in the JSON object, a newline (CRLF in HTTP), and your JSON object. The client just have to count bytes to know when the next byte would be the next objectsize.

      • pros: you keep one long-lived stream.
      • cons: a few extra bytes, you have to keep a long-lived stream, so accidental break and reconnection has to be handled as exceptional events, need to establish some handshaking to continue where it failed.

提交回复
热议问题