要设置PHP Socket的超时时间,您需要在创建套接字后使用settimeo()
函数
$timeout, 'usec' => 0]); socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => $timeout, 'usec' => 0]); // 连接到服务器 $host = '127.0.0.1'; $port = 80; $result = socket_connect($socket, $host, $port); if (!$result) { echo "socket_connect() failed.\nReason: " . socket_strerror(socket_last_error($socket)) . "\n"; exit(); } // 从服务器接收数据 $buffer = ''; socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => $timeout, 'usec' => 0]); $data = https://www.yisu.com/ask/socket_read($socket, 2048, PHP_BINARY_READ);"socket_read() failed.\nReason: " . socket_strerror(socket_last_error($socket)) . "\n"; exit(); } echo "Received data: {$data}\n"; // 关闭套接字 socket_close($socket); ?>
在这个示例中,我们将超时时间设置为10秒。您可以根据需要更改$timeout
变量的值。