Current Location: Home> Latest Articles> The practical application of socket_select in PHP network programming

The practical application of socket_select in PHP network programming

gitbox 2025-05-28

In PHP network programming, the socket_select function is the core tool for implementing multiplexing (I/O multiplexing). It allows the program to listen to multiple sockets at the same time, determine which sockets are readable, writable or have exceptions, avoid blocking and waiting, and thus efficiently handle concurrent connections. This article will combine practical cases to explain the use of socket_select and its application in PHP network programming.


1. The basic principles and functions of socket_select

socket_select is used to monitor a set of socket resources and determine which sockets are ready for read and write operations. The prototype is as follows:

 int socket_select(array &$read, array &$write, array &$except, ?int $tv_sec, ?int $tv_usec = null)
  • $read : Listen to whether it is readable.

  • $write : listen to whether it is writable or not

  • $except : The socket array that listens to exceptions

  • $tv_sec and $tv_usec : timeout (seconds and microseconds)

The function blocks until at least one socket is ready, or a timeout occurs, returning the number of sockets ready.


2. The role of socket_select in the actual development

In actual server development, we often face the situation where multiple client connections arrive at the same time. Using blocking socket_accept cannot handle multiple connections at the same time, which can easily lead to performance bottlenecks. Through socket_select we can:

  • Listen to multiple client connections simultaneously

  • Read data in time when the socket has data, and will not block the CPU when it is idle

  • Implement an efficient event-driven model


3. PHP network programming practical case: multi-client chat room server

The following example implements a simple chat room server that supports multiple client connections and broadcasts messages to everyone.

 <?php
// createTCP Socket
$server = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($server, "0.0.0.0", 12345);
socket_listen($server);

$clients = [];
echo "Chat room server startup,Listen to port12345...\n";

while (true) {
    // Build a listening array,Including serversocketand all clientssocket
    $readSockets = $clients;
    $readSockets[] = $server;

    // usesocket_selectWait for readabilitysocket
    $write = $except = null;
    $numChangedSockets = socket_select($readSockets, $write, $except, 0, 200000);

    if ($numChangedSockets === false) {
        echo "socket_select An error occurred\n";
        break;
    } elseif ($numChangedSockets > 0) {
        // Listen to a new connection
        if (in_array($server, $readSockets)) {
            $newClient = socket_accept($server);
            if ($newClient !== false) {
                $clients[] = $newClient;
                $welcomeMsg = "Welcome to the chat room!\n";
                socket_write($newClient, $welcomeMsg, strlen($welcomeMsg));
                echo "Join the new client,Current connection number:" . count($clients) . "\n";
            }
            // fromreadSocketsRemoved inserver socket,Prevent repeated processing
            $key = array_search($server, $readSockets);
            unset($readSockets[$key]);
        }

        // Process messages sent by the client
        foreach ($readSockets as $sock) {
            $data = @socket_read($sock, 2048, PHP_NORMAL_READ);
            if ($data === false || $data === '') {
                // Client closes the connection
                $key = array_search($sock, $clients);
                socket_close($sock);
                unset($clients[$key]);
                echo "Client disconnection,Current connection number:" . count($clients) . "\n";
                continue;
            }
            $data = trim($data);
            if ($data) {
                echo "Received a message: $data\n";
                // Broadcast messages to all clients
                foreach ($clients as $client) {
                    if ($client != $sock) {
                        socket_write($client, "A user said: $data\n");
                    }
                }
            }
        }
    }
}
socket_close($server);

4. Code analysis

  • The server first creates a TCP socket, binds the port, and listens for the connection.

  • In the main loop, $readSockets contains all client sockets and server listening sockets.

  • Call socket_select to wait for any socket to be readable.

  • If the server socket is readable, there is a new connection, accepted and added to the client list.

  • If the client socket is readable, reads data, closes the connection if empty, otherwise broadcasts the message.

  • Use a non-blocking short timeout of 0.2 seconds to avoid CPU idling.


5. Summary

  • socket_select is the key to multi-connection I/O multiplexing, avoiding blocking and improving server performance.

  • Multi-client concurrent processing can be easily implemented using socket_select .

  • Suitable for chat rooms, online games, instant messaging and other network application scenarios.


If you want to know more detailed tutorials and cases about PHP network programming, you can visit: http://gitbox.net/php-network-tutorial