I've got a chat program which pushes JSON data from Apache/PHP to Node.js, via a TCP socket:
// Node.js (Javascript)
phpListener = net.createServer(function(stream)
{
stream.setEncoding("utf8");
stream.on("data", function(txt)
{
var json = JSON.parse(txt);
// do stuff with json
}
}
phpListener.listen("8887", 'localhost');
// Apache (PHP)
$sock = stream_socket_client("tcp://localhost:8887");
$written = fwrite($sock, $json_string);
fclose($sock);
The problem is, if the JSON string is large enough (over around 8k), the output message gets split into multiple chunks, and the JSON parser fails. PHP returns the $written value as the correct length of the string, but the data event handler fires twice or more.
Should I be attaching the function to a different event, or is there a way to cache text across event fires, in a way that won't succumb to race conditions under heavy load? Or some other solution I haven't thought of?
Thanks!