Note that there are some explanatory texts on larger screens.

plurals
  1. PONodeJS receiving data from PHP server
    primarykey
    data
    text
    <p>I'm currently working on a simple NodeJS client that connects to a PHP server using the net classes. In addition, the NodeJS client is working as a Socket.IO server that sends data received from the PHP server to the browsers connected with Socket.IO.</p> <p>So far, everything is working fine. Yet if I connect with another client to Socket.IO, the PHP server has to send a notification to every connected client. Thus, it sends a JSON-encoded array to the NodeJS client which processes the JSON data (decoding and modifying it a bit).</p> <p>Now the problem is that sometimes two separate messages sent by the PHP server are concatenated in NodeJS' onData event handling function:</p> <pre><code>client.on("data", function(data) { var msgData = JSON.parse(data.toString("utf8")); [...] } </code></pre> <p>The variable <em>data</em> now <strong>sometimes</strong> (not every time!) contains two JSON-strings, such as:</p> <pre><code> { "todo":"message", [...] } { "todo":"message", [...] } </code></pre> <p>This of course results in an exception thrown by the <em>JSON.parse</em> function. I expected two calls of the onData-function with the variable <em>data</em> being:</p> <pre><code>{ "todo":"message", [...] } </code></pre> <p>On the PHP server side I have to iterate over an array containing all Socket.IO-connections that are currently served:</p> <pre><code>foreach($sockets as $id =&gt; $client) { $nodeJS-&gt;sendData($client, array("todo" =&gt; "message", [...]); } </code></pre> <p>The <em>$nodeJS->sendData</em>-function json-encodes the array and sends it to the NodeJS client:</p> <pre><code>socket_write($nodeClient, json_encode($dataToSend)); </code></pre> <p>The <em>$nodeJS->sendData</em> function is definitively called two times, as socket_write is.</p> <p>I now have no idea whether PHP or NodeJS concatenates those two strings. What I want, is that NodeJS calls the onData-handler once for each time the <em>$nodeJS->sendData</em> function is called (e.g. sendData is called twice → the onData-event is fired twice). I could of course add some flag at the end of each json-encoded string and later split them into an array in the onData function. However, I don't like that solution much.</p> <p>Is there an easier way to accomplish this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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