Function name: stream_set_timeout()
Applicable version: PHP 4, PHP 5, PHP 7
Usage: stream_set_timeout(resource $stream, int $seconds, int $microseconds = 0): bool
Function description: stream_set_timeout() is used to set the timeout time of the specified stream. Timeout specifies the maximum time to wait for data when the stream is read or written. If no data is read or written within the timeout time, the function will return false.
parameter:
Return value: Return true if the timeout time is successfully set; otherwise return false.
Example:
// 创建一个TCP 客户端连接$socket = stream_socket_client('tcp://www.example.com:80', $errno, $errstr, 30); if (!$socket) { die("连接失败: $errstr ($errno)"); } // 设置超时时间为5秒if (stream_set_timeout($socket, 5) === false) { die("设置超时时间失败"); } // 发送HTTP请求$request = "GET / HTTP/1.1\r\n"; $request .= "Host: www.example.com\r\n"; $request .= "Connection: close\r\n\r\n"; fwrite($socket, $request); // 读取响应$response = ''; while (!feof($socket)) { $response .= fread($socket, 8192); } // 关闭连接fclose($socket); echo $response;
In the example above, we first create a TCP client connection using the stream_socket_client() function. Then, use the stream_set_timeout() function to set the timeout to 5 seconds. Next, we sent an HTTP request and read the server's response. Finally, the connection is closed and the response is printed.
Please note that setting the timeout time is only applicable to read and write operations and does not affect the connection establishment or closing process.