简体   繁体   English

PHP套接字客户端不接收连续数据

[英]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. 我的目标是捕获Java服务器套接字实时生成的消息,并将这些消息显示在网页上。 I am trying to use php to connect to the socket and receive data from the server. 我正在尝试使用php连接到套接字并从服务器接收数据。 The php client should continuously listen to the server for messages. php客户端应不断侦听服务器中的消息。

Here is my php code 这是我的PHP代码

<?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. 当我加载此php页面时,大多数时候我会收到504网关超时错误。 I have verified that the Java server is picking up the client connection. 我已验证Java服务器正在拾取客户端连接。 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. 不知道为什么,因为我有一个while(true)循环。

Am I using the php socket correctly? 我是否正确使用php套接字? 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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