Function name: stream_set_blocking()
Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7
Usage: stream_set_blocking(resource $stream, bool $mode): bool
Function description: The stream_set_blocking() function is used to set the blocking or non-blocking mode of a given stream.
parameter:
Return value: Return true on success, and false on failure.
Example:
// 创建一个网络套接字流$socket = stream_socket_client('tcp://www.example.com:80', $errno, $errstr, 30); // 将套接字流设置为非阻塞模式if (!stream_set_blocking($socket, false)) { die('无法设置套接字流为非阻塞模式'); } // 发送HTTP请求fwrite($socket, "GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: Close\r\n\r\n"); // 读取响应$response = ''; while (!feof($socket)) { $response .= fread($socket, 8192); } // 关闭套接字流fclose($socket); echo $response;
In the above example, we first create a network socket stream and then use the stream_set_blocking() function to set the socket stream to non-blocking mode. Next, we send an HTTP request and read the response. Finally, close the socket stream and output the response content.
By setting the socket stream to non-blocking mode, we can continue to perform other operations while waiting for a response without having to wait for a response from the server. This is very useful for handling a large number of concurrent requests or where multiple tasks need to be processed simultaneously.