如何使用 Amphp 捕获 php websocket 断开的 TCP 连接异常?

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

这是当前的 WebSocket 循环我 运行 连接仍然有效。但是连续连接11小时后,收到异常

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

如何检查关闭的连接或异常本身?,这样我就可以正确结束脚本逻辑而不会突然失败。

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

我正在使用这个 Amphp Websocket:https://github.com/amphp/websocket-client

谢谢!

我确实找到了解决方案,方法是在它被抛出后寻找 ClosedException 和 运行 其他任务。

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