如何使用 Amphp 捕获 php websocket 断开的 TCP 连接异常?
Posted
技术标签:
【中文标题】如何使用 Amphp 捕获 php websocket 断开的 TCP 连接异常?【英文标题】:How to catch a php websocket broken TCP connection exception with Amphp? 【发布时间】:2019-11-26 18:01:06 【问题描述】:这是我在连接仍然存在时正在运行的当前 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
谢谢!
【问题讨论】:
【参考方案1】:通过查找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
);
【讨论】:
以上是关于如何使用 Amphp 捕获 php websocket 断开的 TCP 连接异常?的主要内容,如果未能解决你的问题,请参考以下文章