Current Location: Home> Function Categories> stream_set_timeout

stream_set_timeout

Set timeout on stream
Name:stream_set_timeout
Category:Stream
Programming Language:php
One-line Description:Set the timeout time for the specified stream

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:

  • $stream: The stream resource to set the timeout time.
  • $seconds: The number of seconds part of the timeout time. If set to 0, there is no timeout limit.
  • $microseconds: The microseconds part of the timeout time. The default value is 0.

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.

Similar Functions
Popular Articles