PHP detecting TCP client disconnect

1.4k views Asked by At

I got a TCP server up and running, which supports many client connections at the same time, together with reading and sending data. However, when client closes the connection, there is a delay on the server to detect a disconnected client.

// TCP socket created here
$clients = array($socket);
while (true) {
    $read = $clients; // Copy of $clients
    $write = NULL;
    $except = NULL;
    $num_changed_sockets = socket_select($read, $write, $except, NULL);
    if ($num_changed_sockets === false) {
        // ...
    } else if ($num_changed_sockets > 0) { // Something changed
        printb("In here."); // EDIT
        if (in_array($socket, $read)) { // For new connections and removing host from the $clients copy
            $newsock = socket_accept($socket);
            if ($newsock !== false) {
                printb("Client $newsock connected");
                $clients[] = $newsock;
            }
            $key = array_search($socket, $read);
            unset($read[$key]);
        }
        foreach ($read as $read_socket) { // The actual problem starts here?
            printb("Read part."); // EDIT
            $data = socket_read($read_socket, 128);
            if ($data === false) {
                printb("Client $read_socket disconnected");
                $key = array_search($read_socket, $clients);
                socket_close($clients[$key]);
                unset($clients[$key]);
                continue;
            }
       }
}

EDIT I: I just added debug prints in the code. When a single client disconnects, server falls into infinite loop from $num_changed_sockets. Is there way to fix it?

EDIT II: var_dump gives empty string after a client has disconnected.

EDIT III: According to last edit, disconnecting the client, if socket_read returns an empty string seems to work. I Found a note from PHP's website:

Note: socket_read() returns a zero length string ("") when there is no more data to read.

Should not this return false, when client disconnects?

0

There are 0 answers