我正在做一个与php socket相关的项目。我的目标是我将显示连接到服务器的所有客户端并在html文件中显示它们。但是,如果我在while循环中放入socket_accept()函数,它将在没有客户端连接时中断,并且它将在那里等待新客户端,因此不会显示html文件。现在,我想while循环只接受10秒内的所有客户端然后导出结果?我尝试过set_time_limit(),但不行。如何在php中打破socket_accept?
<?php
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(10);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = "103.1.239.148";
$port = 10000;
// Maximum device
$maxdevice = 5;
// Create Socket
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($sock === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($sock));
exit;
}
// Bind Socket to port
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
// Start listening for connection
if (socket_listen($sock, $maxdevice) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
// Handling connection from client
$i=0; // Initial count variable
while (true)
{
$msgsock[++$i] = socket_accept($sock); // msgsock is a client connect to webserver
if ($msgsock[$i] === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
$senddata="L";
socket_write($msgsock[$i], $senddata, strlen($senddata)) or die("Couldn't write to client");
$receive=socket_read($msgsock[$i],2048,PHP_BINARY_READ) or die ("Couldn't read from client");
if ($receive !="")
{
include ("list.html");
}
if ($i==$maxdevice)
break;
socket_close($msgsock[$i]); // Close connect of client
}
socket_close($sock); // Close socket of server
?>