我一直在寻找来解决这个问题的解决方案。似乎socket_select()
总是会找到可接受的套接字(由socket_accept()
所返回的资源)以供读取,即使没有等待的数据包也是如此。我确定有些事情我忘了做,但是我不知道那是什么。
以下是相关代码:
while(TRUE){
$read_sockets=$this->client_sockets;
$write_sockets=NULL;
$except=NULL;
if(socket_select($read_sockets, $write_sockets, $except, NULL)<1) continue;
foreach($read_sockets as $pending_socket){
echo "Read request received...".PHP_EOL;
if($this->socket==$pending_socket){
$new_client_socket=socket_accept($this->socket);
socket_write($new_client_socket,$this->read_data($new_client_socket),2048);
$this->client_sockets[]=$new_client_socket;
echo "New client...".PHP_EOL;
} else {
$pending_socket_data=$this->read_data($pending_socket);
if($pending_socket_data===false){
unset($this->client_sockets[array_search($pending_socket,$this->client_sockets)]);
continue;
}
socket_write($pending_socket,$pending_socket_data,2048);
echo "Old client...".PHP_EOL;
}
}
}
private function read_data(&$socket){
echo 'Reading data...'.PHP_EOL;
$client_data='';$tmp='';
while(socket_recv($socket,$tmp,$this->max_length,0) > 0){
$client_data .= $tmp;
}
return $client_data;
}
我知道我没有捕捉到一些异常,例如socket_recv === FALSE,但是此代码只是概念证明,我在调试主代码时必须认真研究。
$this->socket
是服务器套接字,并且是非阻塞的。
提前致谢!
private function read_data(&$socket){
echo 'Reading data...'.PHP_EOL;
$client_data='';$tmp='';
while(socket_recv($socket,$tmp,$this->max_length,0) > 0){
$client_data .= $tmp;
}
return $client_data;
}
方法read_data
永远不会返回false,因此以下代码将永远不会运行。
if($pending_socket_data===false){
unset($this->client_sockets[array_search($pending_socket,$this->client_sockets)]);
continue;
}
当socket_recv
返回false,你应该检查socket_last_error()
并决定是否要socket_close($pending_socket)
和unset($this->client_sockets[..])
。
当socket_recv
返回0时,可能是套接字关闭的,应该调用unset($this->client_sockets[..])
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句