这是连接仍处于活动状态时我正在运行的当前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
谢谢!
答案 0 :(得分:0)
我确实找到了解决方案,方法是查找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
}
}
);