Php socket_write works for the first time but

I am contacting to write multiple messages (each message created dynamically) to a device through a single socket created using PHP. The first message always passes; but subsequent messages do not pass. To help me debug, let me know if there is a problem with this example:

        $socket= socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        socket_connect($socket, $ip, $port); 
        socket_write($socket, "message 1\r");
        socket_write($socket, "message 2\r");
+3
source share
1 answer

Have you tried adding carriage return to socket_write($socket, "message 1\r\n");at the end of the message? In many cases, when working with buffers and threads, this seems to do the trick.

Something else worth doing:

//all suggestions rolled into one (including Chris' chr(0) - thanks for that one)
socket_write($socket, 'message 1'."\r\n".chr(0));
usleep(5);
socket_write($socket, 'Foobar'."\r\n".chr(0));

just giving a little extra time to flush the buffer can do wonders.

EDIT

I had another brain wave: did you also try to use the extra length parameter?

socket_write($socket, 'message 1'."\r\n".chr(0),strlen('message 1'."\r\n".chr(0)));
+3
source

All Articles