PHP socket write and then read is blocking the socket

I have a Java server that is listening requests, and a PHP page that is sending those requests.

Once I am connected to the server, I write something with the "socket_write" command, and then I try to read the server answer with "socket_read". (instead of waiting for answers, I would like to know how to synchronise the two programs correctly, with semaphore for example).

Here is the code :

$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);

$con = socket_connect($socket, "127.0.0.1",6543);

//Connected, we can ask


$message = "SLICE";
socket_write($socket,$message,strlen($message));

$buf = socket_read($socket,2048,PHP_NORMAL_READ);

echo $buf;

socket_close($socket);

The java server listens to requests using the InputStream of the socket. When I comment the two lines $buf = socket_read and echo $buf, the server is able to get the "SLICE" message. But if I leave it like this, it seems that PHP writes into the socket and then directly monopolizes the socket by trying to read it, before my java server is able to read the socket !

And then my Java server is infinitely blocked on the "readline();" while the PHP is also blocked on socket_read.

How to synchronise all of this ?


As per James Lockhart's comment, this is the solution:

Without knowing what the Java code is doing I could only hazard a guess what you need a linebreak or something? Try $message = "SLICE" . PHP_EOL;

链接地址: http://www.djcxy.com/p/78380.html

上一篇: 为什么要将“”添加到字符串保存内存?

下一篇: PHP套接字写入然后读取是阻塞套接字