1

I have a PHP socket application which connects to a server and sends some data,

i need to extend this script to send (write) and listen back for a replay from the server

i was trying using socket_read() after socket_write()

but it hangs the script.

any idea on this ?

9
  • 1
    Isn't that the expected state? it should block until data is received. Commented Jun 20, 2011 at 21:03
  • actually im sending the message from the server Commented Jun 20, 2011 at 21:04
  • You can find some PHP socket code here: Writing Socket Servers in PHP Commented Jun 20, 2011 at 21:06
  • 1
    Ensure that the socket you open is full-duplex an actually open to read data, not only to send data. You should show more code so that could actually be seen. Commented Jun 20, 2011 at 21:07
  • What is $file_bits? Assuming it's valid, that code will wait until timeout to read from the socket at least one byte. Commented Jun 20, 2011 at 21:16

2 Answers 2

3

socket_read() is blocking. It hangs until there's something to read. Also, you will need to call it repeatedly until it returns an empty string (concatenating what you got so far), and only then will you give the full reply.

This is how socket operations work:

socket_write($socket, 'request');
$response = '';
do {
    $buffer = socket_read($socket, $number_of_bytes_to_read);
    $response .= $buffer;
} while (!empty($buffer));
Sign up to request clarification or add additional context in comments.

2 Comments

actually im sending the message from the server its not reading by socket_read(
@Sudantha, I'm not sure I understand what you mean by that.
1

for a workaround add a sleep(1) after the write, then start reading.

Check the return value of the write operation as well first. Does return the number of bytes written, FALSE on error.

1 Comment

Please don't add sleep(1)

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.