错误代码示例:
Master::$globalEvent = new EventLoop();
Master::$globalEvent->add($mainSocket, function ($sock) {
$newSocket = stream_socket_accept($sock, 0, $remoteAddress);
\stream_set_blocking($newSocket, 0);
// Compatible with hhvm
if (\function_exists('stream_set_read_buffer')) {
\stream_set_read_buffer($newSocket, 0);
}
echo 'remote address : ' . $remoteAddress . PHP_EOL;
// error1 $res = Master::$globalEvent->add($newSocket, [TcpConn::class, 'readBak'], 'stream_socket_accept');
//error2
$res = Master::$globalEvent->add($newSocket, function ($socket) {
$buff = fread($socket, 65536);
echo "客户端请求来了~\n";
echo $buff . "\n";
fwrite($socket, "HTTP/1.1 200 OK\r\nAccept: application/json, text/plain, */*\r\nConnection: keep-alive\r\nContent-Length: 6\r\n\r\nhello~");
// }, 'stream_socket_accept');
}, 'stream_socket_server');
Master::$globalEvent->loop();
在第一次stream_socket_server之后,把服务端socket添加进事件循环之后,在这个事件循环的闭包里,再次stream_socket_accept这个方法的调用,把新的连接再次丢入事件循环,这个时候,第二个闭包放的代码不会执行