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 practise with regard to sending multiple JSON messages over a plain TCP socket?
Some alternatives I have looked at (and their downsides) are:
Is there a good, or at least well-established way of doing this?
json file. JSON over HTTP(s) is one of the preferred REST API protocols because it is built on top of http. M2M API protocols based on http tend to be the most reliable with respect to enterprise IT environments, security mechanisms, blocked ports etc.
The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.
JSON is a wildly successful way of formatting data for several reasons. First, it's native to JavaScript, and it's used inside of JavaScript programs as JSON literals. You can also use JSON with other programming languages, so it's useful for data exchange between heterogeneous systems. Finally, it is human readable.
my first two options would be:
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.
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.
When you want to serve browser clients, the closest you get to raw TCP is WebSockets.
WebSockets has sufficient momentum that browser vendors will improve support (Chrome 14 and Firefox 7/8 support the latest protocol draft) and that a broad range of client and server frameworks will support it.
There are already a couple of open-source client libraries, including Autobahn WebSocket.
When you want to bake something for your own (on top of raw TCP), I would recommend a length-prefixed format for your JSON messages, i.e. Netstrings
Disclaimer: I am author of Autobahn and work for Tavendo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With