phpwebsocketphpwebsocketamphp

How to catch a php websocket broken TCP connection exception with Amphp?


Here is the current WebSocket loop I'm running while the connection is still alive. But after 11 hours of continuous connection, I received an exception

"exception":"[object] (Amp\\Websocket\\ClosedException(code: 1006): The connection was closed: Client closed the underlying TCP connection at ...

How can I check for the closed connection or the exception itself?, this way I can properly end the script logic without an abrupt failure.

     \Amp\Loop::run(function () use ($fn, $st)
        {
            $connection = yield \Amp\Websocket\connect('wss://URL');

            yield $connection->send('{"action":"auth","params":"KEYID"}');
            yield $connection->send('{"action":"subscribe","params":"'.$st.'"}');

            $i = 0;

            while ($message = yield $connection->receive()) 
            {
                $i++;
                $payload = yield $message->buffer();

                $r = $fn($payload, $i);

                if ($r == false) {
                    $connection->close();
                    break;
                }
            }
        }
    );

I am using this Amphp Websocket: https://github.com/amphp/websocket-client

Thanks!


Solution

  • I did find a solution to this by looking for the ClosedException and running other tasks after it has been thrown.

    \Amp\Loop::run(function () use ($fn, $st)
        {
            try 
            {
                $connection = yield \Amp\Websocket\connect('wss://URL');
    
                yield $connection->send('{"action":"auth","params":"KEYID"}');
                yield $connection->send('{"action":"subscribe","params":"'.$st.'"}');
    
                $i = 0;
    
                while ($message = yield $connection->receive()) 
                {
                    $i++;
                    $payload = yield $message->buffer();
    
                    $r = $fn($payload, $i);
    
                    if ($r == false) {
                        $connection->close();
                        break;
                    }
                }
            }
            catch (\Amp\Websocket\ClosedException $e) 
            {
                // do something here
            }
        }
    );