0

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

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 循环并检查是否同时有消息会很酷,这可能吗?

4

1 回答 1

1

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);
  }
});
于 2020-04-27T19:29:19.527 回答