Note that there are some explanatory texts on larger screens.

plurals
  1. POIssues when reading a string from TCP socket in Node.js
    text
    copied!<p>I've implemented a client/server that communicate using a TCP socket. The data that I'm writing to the socket is stringified JSON. Initially everything works as expected, however, as I increase the rate of writes I eventually encounter JSON parse errors where the beginning on the client receives the beginning of the new write on the end of the old one. </p> <p>Here is the server code:</p> <pre><code>var data = {}; data.type = 'req'; data.id = 1; data.size = 2; var string = JSON.stringify(data); client.write(string, callback()); </code></pre> <p>Here is how I am receiving this code on the client server:</p> <pre><code>client.on('data', function(req) { var data = req.toString(); try { json = JSON.parse(data); } catch (err) { console.log("JSON parse error:" + err); } }); </code></pre> <p>The error that I'm receiving as the rate increases is:</p> <pre><code>SyntaxError: Unexpected token { </code></pre> <p>Which appears to be the beginning of the next request being tagged onto the end of the current one.</p> <p>I've tried using ; as a delimiter on the end of each JSON request and then using:</p> <pre><code> var data = req.toString().substring(0,req.toString().indexOf(';')); </code></pre> <p>However this approach, instead of resulting in JSON parse errors seems to result in completely missing some requests on the client side as I increase the rate of writes over 300 per second.</p> <p>Are there any best practices or more efficient ways to delimit incoming requests via TCP sockets?</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload