我在这里使用自述文件示例:
https://github.com/amphp/websocket-client/blob/master/README.md
use Amp\Websocket;
use Amp\Delayed;
use Amp\Websocket\Connection;
use Amp\Websocket\Handshake;
use Amp\Websocket\Message;
use function Amp\Websocket\connect;
\Amp\Loop::run(function () use ($fn)
{
try
{
$connection = yield connect('wss://....');
yield $connection->send('{
"action":"authenticate",
"data":{
...
}
}');
while ($message = yield $connection->receive())
{
$payload = yield $message->buffer();
// print the payload
$this->info($payload);
// custom function to parse the payload
$r = $fn($payload);
if ($r == false) {
$this->warn('Connection closed.');
$connection->close();
break;
}
}
}
catch (\Throwable $e) {
$this->isError($e->getMessage(),true);
}
catch (\Exception $e) {
$this->isError($e->getMessage(),true);
}
});
问题:while 循环只会在通过流发送消息时运行,没有消息,什么都不会发生,因为它处于空闲模式等待。
解决方案:如何接收 ping 或在 ping 上运行 while 循环,并且仍然收集消息?
例如,我想控制检查一些信息,(例如套接字应该保持打开)但是,它只能检查当消息通过流时,这会限制脚本,因为它只会在何时执行有一个活动,因此如果没有发送任何信息,则永远等待。
Ping 是基于 RFC 的 Web 套接字中的标准:https ://www.rfc-editor.org/rfc/rfc6455
在Rfc6455Connection
连接类中,有 ping,但没有关于如何访问或直接使用它的文档。
在 ping 上运行 while 循环并检查是否同时有消息会很酷,这可能吗?