阅读量:0
要设置PHP Socket的超时时间,您需要在创建套接字后使用settimeo()
函数
<?php // 创建一个新的socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$socket) { echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n"; exit(); } // 设置超时时间(秒) $timeout = 10; socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => $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 = socket_read($socket, 2048, PHP_BINARY_READ); if ($data === false) { echo "socket_read() failed.\nReason: " . socket_strerror(socket_last_error($socket)) . "\n"; exit(); } echo "Received data: {$data}\n"; // 关闭套接字 socket_close($socket); ?>
在这个示例中,我们将超时时间设置为10秒。您可以根据需要更改$timeout
变量的值。