Connection undoing while running php socket script

Asked

Viewed 174 times

0

I am setting up a socket server in php, a simple chat. When I send a message or close a page, the following error appears: "Warning: socket_recv() Unable to read from socket[10053] An established connection was cancelled by the software on the host computer" and on the other line the same message, only with socket_write(), this only happens when I put socket_write to send messages to all clients, see a snippet of code:

foreach($read as $read_socket){
$bytes = socket_recv($read_socket, $data, 1024, null);
if($bytes === 0){
    $key = array_search($read_socket, $array_clients);
    unset($array_clients[$key]);
    echo PHP_EOL . "Cliente desconectado...";
}else{
    foreach($array_clients as $clients)
        socket_write($clients, $data, strlen($data));
}

}

inserir a descrição da imagem aqui

This is very strange because I have already disabled the firewall and Avast and the error continues. Whenever a client disconnects and socket_write() is not present, the "Client disconnected..." message usually appears, only if I echo $data inside Else to show messages from other clients, it appears " Ú" and then the message that the client was disconnected. Could you help me?

1 answer

0

I made a change in the code and ran, logically it was a gambiarra and that can give problem at any time because I realized that the strange symbol " Ú" returns 8 bytes by the socket_recv function, so I had to put an if to avoid sending it, but as I said, this was a trick because short messages with less than 3 characters are not sent.

foreach($read as $changed_socket){
            $bytes = socket_recv($changed_socket, $data, 2048, null);

            if($bytes === 0){
                unset($array_clients[array_search($changed_socket, $array_clients)]);
                echo "Cliente $changed_socket desconectado.";
            }elseif($bytes === false){
                $this->sock_error();
            }else{
                if($bytes>8){
                    $msg = "MSG($changed_socket):" . $this->unmask($data) . "<br />";
                    $msg = $this->mask($msg);
                    foreach($array_clients as $conectados)
                        socket_write($conectados, $msg, strlen($msg));
                }
            }

        }

The following is, when the client disconnects, first the socket_recv receives a message (This should not happen) that in the case is these strange symbols " Ú", in the next loop is that it actually disconnects the client and displays the message "Client disconnected...". This is very strange, because the right one would be, as soon as socket_select notices a change in $read, it should immediately pass the socket that wants to close the connection, however it only does this in the next loop, how can I solve this problem? Could it be memory junk?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.