What are some best practices for handling multiple clients in a PHP socket server?

When handling multiple clients in a PHP socket server, it is important to use non-blocking I/O operations and implement a mechanism to manage multiple client connections concurrently. One common approach is to use a loop to continuously check for new client connections and handle each client in a separate thread or process.

<?php

$server = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr);

if (!$server) {
    die("Error creating socket: $errstr ($errno)");
}

$clients = [];

while (true) {
    $read = $clients;
    $read[] = $server;

    if (stream_select($read, $write, $except, 0) > 0) {
        if (in_array($server, $read)) {
            $client = stream_socket_accept($server);
            $clients[] = $client;
        }

        foreach ($clients as $key => $client) {
            $data = fread($client, 1024);
            if ($data) {
                // Handle client data
                fwrite($client, "Response to client");
            } else {
                fclose($client);
                unset($clients[$key]);
            }
        }
    }
}

fclose($server);
?>