How can the PHP script be modified to display the client counter for each server port simultaneously?

To display the client counter for each server port simultaneously, we can modify the PHP script to keep track of the client count for each port separately. We can achieve this by using an associative array where the keys are the server ports and the values are the client counts. Then, we can update the client count for each port accordingly when a new client connects or disconnects.

<?php
$clients = []; // Associative array to store client count for each port

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

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

echo "Server started on port 8000\n";

while (true) {
    $read = [$server];
    $write = null;
    $except = null;

    if (stream_select($read, $write, $except, 0) > 0) {
        $client = stream_socket_accept($server);

        $clientPort = explode(":", stream_socket_get_name($client, true))[1];

        if (!isset($clients[$clientPort])) {
            $clients[$clientPort] = 0;
        }

        $clients[$clientPort]++;

        echo "Client connected on port $clientPort\n";

        fwrite($client, "Connected to server on port $clientPort\n");

        fclose($client);

        $clients[$clientPort]--;
        echo "Client disconnected on port $clientPort\n";
    }
}
?>