简体   繁体   中英

php socket client not receiving continuous data

My goal is capture messages being generated in real time by a Java server socket and display these messages on the webpage. I am trying to use php to connect to the socket and receive data from the server. The php client should continuously listen to the server for messages.

Here is my php code

<?php
set_time_limit(0);

$serverAddress=SERVER_ADDRESS;
$serverListeningPort=SERVER_PORT;
//make a connection and get a socket object
if ( ($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === FALSE )
{
    echo "socket_create() failed: reason: " .socket_strerror(socket_last_error());
}
else
{
    echo("socket create was successful");
    echo("<br>");
}
echo ("Attempting to connect to host");
echo("<br>");
if ( ($result = socket_connect($socket, $serverAddress, $serverListeningPort)) === FALSE )
{

    echo ("socket_connect() failed. Reason:".socket_strerror(socket_last_error($socket)));
}
echo ("Reading response:");
$message="";
while(true)//listen for ever
{
  $message=socket_read($socket, 300);
  if($message!=='')
  {
   print_r($message);
  }
}                       
?>

When I load this php page, most of the time I get a 504 gateway time out error. I have verified that the Java server is picking up the client connection. Sometimes, I get a few messages only and then the page stops getting messages from the server. Not sure why, as I have a while(true) loop.

Am I using the php socket correctly? How can I accomplish my goal.

Thank you

Try adding the below lines at the start of your code. This will output the result to browser as it is generated.

ob_end_flush();
ob_implicit_flush(1);

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