Current Location: Home> Function Categories> stream_set_blocking

stream_set_blocking

Set blocking or blocking mode for resource flow
Name:stream_set_blocking
Category:Stream
Programming Language:php
One-line Description:Sets blocking or non-blocking mode for a given stream

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:

  • $stream: The stream resource to set the mode.
  • $mode: Specifies the mode of the stream. If $mode is true, the stream will be set to blocking mode; if $mode is false, the stream will be set to non-blocking mode.

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.

Similar Functions
Popular Articles