socket_select永不过时
socket_select never time out
我一直在尝试制作一个 PHP 套接字服务器,这是我以前从未做过的事情。所以我可能不明白所有 socket_* 函数是如何工作的。
我遇到的问题是socket_select中的超时功能。
while(true){
//Copy $clients so the list doesn't get modified by socket_select();
$read = $clients;
$write = $clients;
//new socket tries to connect
if(!$new = socket_accept($socket)){
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error()); break;
}
//Accept the new client
if(!in_array($new, $clients)){
$clients[] = $new;
sendMessage($new, "Hello and welcome to the PHP server!");
}
//Wait for read
socket_select($read, $write, $empty, 5, 5);
foreach($read as $client){
$id = array_search($client,$clients);
echo $id." ".readMessage($client);
}
//Write data to the connected sockets
foreach($write as $client){
sendMessage($client, rand(0,99999));
}
echo "I'm bored\n";
}
根据我对 socket_select 的理解,该脚本应该每 5 秒说 "I'm bored"。但是没有,为什么?
为什么我要超时 socket_select 是为了做一个循环,这样我就可以将数据发送到连接的套接字。
您每次都在循环中调用 socket_accept()
。如果没有新连接到达,此调用将阻塞。
将 $socket
添加到传递给 socket_select()
的套接字数组中,并且仅当该套接字显示为可读时才调用 socket_accept()
。 (您还需要使该套接字成为其他循环中的异常,这样您就不会尝试写入它。)
我一直在尝试制作一个 PHP 套接字服务器,这是我以前从未做过的事情。所以我可能不明白所有 socket_* 函数是如何工作的。
我遇到的问题是socket_select中的超时功能。
while(true){
//Copy $clients so the list doesn't get modified by socket_select();
$read = $clients;
$write = $clients;
//new socket tries to connect
if(!$new = socket_accept($socket)){
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error()); break;
}
//Accept the new client
if(!in_array($new, $clients)){
$clients[] = $new;
sendMessage($new, "Hello and welcome to the PHP server!");
}
//Wait for read
socket_select($read, $write, $empty, 5, 5);
foreach($read as $client){
$id = array_search($client,$clients);
echo $id." ".readMessage($client);
}
//Write data to the connected sockets
foreach($write as $client){
sendMessage($client, rand(0,99999));
}
echo "I'm bored\n";
}
根据我对 socket_select 的理解,该脚本应该每 5 秒说 "I'm bored"。但是没有,为什么?
为什么我要超时 socket_select 是为了做一个循环,这样我就可以将数据发送到连接的套接字。
您每次都在循环中调用 socket_accept()
。如果没有新连接到达,此调用将阻塞。
将 $socket
添加到传递给 socket_select()
的套接字数组中,并且仅当该套接字显示为可读时才调用 socket_accept()
。 (您还需要使该套接字成为其他循环中的异常,这样您就不会尝试写入它。)