Current Location: Home> Function Categories> stream_select

stream_select

Run the select() system call on the given stream array and use the timeout specified by tv_sec and tv_usec
Name:stream_select
Category:Stream
Programming Language:php
One-line Description:Wait in a given set of file streams until one or more of the file streams has a readable, writable, or exceptional event

Function name: stream_select()

Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7

Function Description: The stream_select() function is used to wait in a given set of file streams until one or more of the file streams have readable, writable, or exceptional events. It is a very common function in network programming and can be used to create efficient I/O multiplexers.

Syntax: int stream_select ( array &$read , array &$write , array &$except , int $tv_sec [, int $tv_usec = 0 ] )

parameter:

  • $read: an array containing the readable streams to be checked.
  • $write: an array containing the writeable streams to be checked.
  • $except: An array containing the exception stream to be checked.
  • $tv_sec: Sets the number of seconds to wait.
  • $tv_usec: Sets the number of microseconds of waiting time.

Return value: The number of streams that occur before timeout, or return false in case of an error.

Example:

 $socket1 = stream_socket_client("tcp://www.example.com:80", $errno, $errstr, 30); $socket2 = stream_socket_client("tcp://www.example.net:80", $errno, $errstr, 30); $socket3 = stream_socket_client("tcp://www.example.org:80", $errno, $errstr, 30); $read = array($socket1, $socket2, $socket3); $write = $except = null; if (stream_select($read, $write, $except, 5)) { foreach ($read as $socket) { $data = fread($socket, 1024); // 对读取到的数据进行处理} } else { // 超时或出错处理}

In the example above, we create three TCP connections and put them into the $read array. Then, we call stream_select() function to wait for any readable events to occur on these connections, with a waiting time of 5 seconds. If a readable event occurs within the timeout time, we use fread() function to read the data and process it. If a timeout or an error occurs, we can handle it accordingly as needed.

Note that stream_select() function is blocking, i.e. the script will pause execution during the wait until the event occurs or timeout. Therefore, it usually needs to be used in conjunction with non-blocking mode streams to fully utilize its advantages.

Similar Functions
Popular Articles