简体   繁体   中英

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!

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
        }
    }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM