Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP socket_write works first time, but

Tags:

php

sockets

I am tying to write several messages (each message created dynamically) to a device through one socket created with PHP. The first message always goes through; but, subsequent messages do not go through. To help me debug, please 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");
like image 784
John R Avatar asked Sep 10 '26 06:09

John R


1 Answers

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

Something else worth giving a shot:

//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 that little bit of extra time to clear the buffer can do wonders.

EDIT

Just had another brain wave: have you tried using the optional length parameter, too?

socket_write($socket, 'message 1'."\r\n".chr(0),strlen('message 1'."\r\n".chr(0)));
like image 85
Elias Van Ootegem Avatar answered Sep 12 '26 20:09

Elias Van Ootegem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!