Current Location: Home> Function Categories> socket_select

socket_select

Run the select() system call on the specified timeout socket array
Name:socket_select
Category:Sockets
Programming Language:php
One-line Description:Multiplexing of blocking I/O operations on a given set of sockets

Function name: socket_select()

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

Function description: The socket_select() function is used to multiplex blocking I/O operations on a given set of sockets. It can monitor multiple sockets simultaneously to determine which sockets have input, output, or exception events occur. This function is implemented based on the select system call provided by the operating system.

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

parameter:

  • $read: an array of sockets that need to monitor read events.
  • $write: an array containing sockets that need to monitor write events.
  • $except: an array of sockets that need to monitor exception events.
  • $tv_sec: Timeout time in seconds. If 0, it means infinite waiting.
  • $tv_usec: The microsecond part of the timeout time. The default value is 0.

Return value:

  • If at least one socket is ready for reading, writing, or has an exception, the return value is greater than 0.
  • If the timeout time reaches, the return value is 0.
  • If an error occurs, the return value is -1.

Example:

 $serverSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($serverSocket, '127.0.0.1', 8888); socket_listen($serverSocket); $clientSockets = array($serverSocket); $write = $except = array(); while (true) { $read = $clientSockets; // 用于监视读事件的socket数组// 使用socket_select()等待事件发生if (socket_select($read, $write, $except, 0) < 1) { continue; } // 检查是否有新的客户端连接if (in_array($serverSocket, $read)) { $clientSocket = socket_accept($serverSocket); $clientSockets[] = $clientSocket; echo "New client connected." . PHP_EOL; // 从读事件数组中移除服务器socket $key = array_search($serverSocket, $read); unset($read[$key]); } // 处理已连接的客户端发送的数据foreach ($read as $clientSocket) { $data = socket_read($clientSocket, 1024); if ($data === false) { // 客户端断开连接$key = array_search($clientSocket, $clientSockets); unset($clientSockets[$key]); socket_close($clientSocket); echo "Client disconnected." . PHP_EOL; } else { // 处理客户端发送的数据echo "Received data: " . $data . PHP_EOL; } } } // 关闭服务器socket socket_close($serverSocket);

The above example demonstrates a simple TCP server that uses the socket_select() function to implement multiplexing. In the loop, wait for the event to occur through socket_select(), and then handle different situations according to the return result, such as new client connection, client disconnection and receiving data sent by the client. This method can handle multiple client connections simultaneously in a single thread, improving server performance and concurrent processing capabilities.

Similar Functions
Popular Articles