Chris
Chris

Reputation: 1037

How to get a PHP script to stop buffering socket outputs

I have two PHP scripts that are communicating via a local UNIX socket. The code on one script looks like this:

socket_write($client, "SomeData\n");
socket_write($client, "OtherData\n");
//wait for input, or do some 'lengthy' calculations
socket_write($client, "LastData\n");

And the code on the client side is simply

@socket_select($read,$write,$except,null);
foreach ($read as $socket) {
    echo "Received from socket: ".socket_recv($socket, $buffer, $maxBuffer, 0)."\n";
}

My problem is that two consecutive calls to socket_write() appear to be buffered, such that the output looks like this:

Received from socket: SomeData
OtherData
Received from socket: LastData

Obviously it is not a big deal above, but in reality, I am passing JSON objects, and they are colliding like so:

{"response":"loginOK", "token":"123456"}{"response":"data","x":12, "y":34}

This causes a parse error on the client side. I have no guarantee that certain functions will be called right after another or with a delay in-between, so there is no way I can reliably collate the results into one JSON object. Is there any way to get each socket_write() call to result to one receive event on the client side?

Upvotes: 1

Views: 595

Answers (1)

N1ghtwish
N1ghtwish

Reputation: 41

Use socket_read() with PHP_NORMAL_READ flag, instead of socket_recv(). socket_read() with this flag will exit on \r or \n or \0 bytes and return buffer read till those chars will appear (but watch out, the returned string will contain exit character at the end! You can rid of it using rtrim()). After socket_read() check for the socket with socket_select() again. Please see https://www.php.net/manual/en/function.socket-read.php

Upvotes: 1

Related Questions