3

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");
2
  • what does echo socket_strerror() give you? Commented May 11, 2012 at 21:22
  • @pduersteler placed immediately after socket_write gives a '0' or socket_strerror(socket_last_error()) gives "Unknown error: 0" Commented May 11, 2012 at 22:42

1 Answer 1

3

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)));
Sign up to request clarification or add additional context in comments.

14 Comments

I will try messing with usleep(5). I am currently ending the messages with '\r'. (I will edit to reflect the '\r')
@JohnR: ending with \r won't do, best to use either \n (UNIX) or \r\n (windows). \r is sort of windows-y but not quite there... so I strongly advise you to use \r\n :P
In addition to the line ending suggestion, the program on the other end might be waiting for a null byte terminated chunk. $nullByte = chr(0); That had me scratching my own head last week...
@chris , I'm not clear; should that be placed after the socket write line?
@EliasVanOotegem , Thanks! What worked for me was usleep(500000) . usleep is in microseconds, so that is half a second. I will shorten the duration some, but it fixed the problem.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.