I have implemented a client / server that communicates using a TCP socket. The data I write to the socket is lowercase JSON. Initially, everything works as expected, however, as I increase the write speed, I eventually encounter JSON parsing errors when the client starts getting a new record at the end of the old one.
Here is the server code:
var data = {}; data.type = 'req'; data.id = 1; data.size = 2; var string = JSON.stringify(data); client.write(string, callback());
This is how I get this code on the client server:
client.on('data', function(req) { var data = req.toString(); try { json = JSON.parse(data); } catch (err) { console.log("JSON parse error:" + err); } });
The error that I get with increasing speed is:
SyntaxError: Unexpected token {
It seems that the beginning of the next query is marked at the end of the current one.
I tried to use; as a separator at the end of each JSON request, and then using:
var data = req.toString().substring(0,req.toString().indexOf(';'));
However, this approach, instead of leading to JSON parsing errors, seems to lead to the complete absence of some client-side requests, as I increase the write speed by more than 300 per second.
Are there any recommendations or more efficient ways to differentiate incoming requests over TCP sockets?
Thanks!
source share