John R
John R

Reputation: 3036

PHP socket_write works first time, but

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");

Upvotes: 3

Views: 4582

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

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)));

Upvotes: 3

Related Questions