简体   繁体   中英

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM