我刚开始学习php中的socket编程。我实现了socket_select来处理多个连接。但是该函数还返回没有数据要读取的套接字,这导致阻塞的socket_read函数。代码如下:
function main() {
global $__sockets;
$ssock = createServerSocket("192.168.0.11","8080");
$__sockets[] = $ssock;
$write = array();
$except = array();
$run = 1;
while ($run) {
usleep(100000);
$read_sockets = $__sockets;
echo "Waiting for action...\n";
$select = socket_select($read_sockets, $write, $except, NULL);
if ( $select === false) {
echo "socket_select() failed, Reason: " .
socket_strerror(socket_last_error()) . "\n";
}
echo "Number of changes from socket_select(): $select\n";
echo "Number of sockets in read_sockets: ".count($read_sockets)."\n";
foreach ($read_sockets as $socket) {
echo "Action detected in Socket: ".$socket."\n";
}
if (in_array($ssock, $read_sockets)) {
$__sockets[] = $newsock = @socket_accept($ssock);
socket_getpeername($newsock, $ip);
echo "New connection from: $ip. ID: ".$newsock."\n";
continue;
}
foreach ($read_sockets as $read) {
echo "Reading...$read\n";
if (false === ($buf = socket_read ($read, 2048, PHP_NORMAL_READ))) {
echo "socket_read() failed. Reason: " . socket_strerror(socket_last_error($read)) . "\n";
break;
}
echo $buf."\n";
}
}
}
输出:
Waiting for action...
Number of changes from socket_select(): 1
Number of sockets in read_sockets: 1
Action detected in Socket: Resource id #4
New connection from: 192.168.0.24. ID: Resource id #5
Waiting for action...
Number of changes from socket_select(): 1
Number of sockets in read_sockets: 1
Action detected in Socket: Resource id #5
Reading...Resource id #5
客户端只使用Putty Telnet连接。没有用户输入。 Socket_select指示此套接字上的更改,但socket_read阻止并且不获取任何数据。有任何想法如何解决这个问题?