繁体   English   中英

使用 Amp\\Websocket 从开放流连接获取 websocket ping?

[英]Get websocket pings from an open stream connection using Amp\Websocket?

我在这里使用自述文件示例:

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 : //tools.ietf.org/html/rfc6455

Rfc6455Connection连接类中,有 ping,但没有关于如何访问它或直接使用它的文档。

在 ping 上运行 while 循环并同时检查是否有消息会很酷,这可能吗?

amphp/websocket-client自动处理 ping 并响应它们,因此接收消息是 API 用户唯一应该关心的问题。

使用 Amp,您可以随时使用Amp\\call / Amp\\asyncCall生成多个协程,因此您可以在一些空闲时间后关闭连接。

Loop::run(function () {
    try {
      $connection = yield connect($uri);

      asyncCall(function () use ($connection) {
        while (true) {
          if (!$this->isActive()) {
            $connection->close();
            break;
          }

          yield Amp\delay(1000);
        }
      });

      yield $connection->send('...');

      while ($message = yield $connection->receive()) {
          $payload = yield $message->buffer();

          $r = $fn($payload);

          if ($r == false) {
              $this->warn('Connection closed.');
              $connection->close();
              break;
          }
      }
  } catch (\Exception $e) {
      $this->isError($e->getMessage(),false);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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