簡體   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