Ratchet Pawl: unable to send message to websocket in loop

时间:2019-03-19 15:19:03

标签: ratchet reactphp

I need to read data from a serial port and send it to a websocket. I loop into a while and when some data arrives I throw it out.

Given the code below, which is a very little modification from Pawl's loop example, the send() is never executed and I cannot figure out why. I tried the sending code in a standalone php and it works, but when I add it into the while loop it looks like it's never executed. I see the INVIO debug but then it goes back to LOOP, and no message is broadcasted.

I tried even the easier example without React's loop but behaves exactly the same, send() is apparently never reached.

        $loop = \React\EventLoop\Factory::create();
        $reactConnector = new \React\Socket\Connector($loop, [
          'dns' => '8.8.8.8',
          'timeout' => 10
        ]);
        $connector = new \Ratchet\Client\Connector($loop, $reactConnector);

        $loop->addPeriodicTimer(8, function () use($connector){
            echo "LOOP\n";
            do {
                sleep(1);
                $msg = $this->getSerial()->read();
//              $msg = $this->getSerial()->readPort();
                echo "LETTO <$msg>\n";
           } while (strlen($msg) < 50);
                echo "INVIO $msg\n";
                $connector('ws://127.0.0.1:9988')
                  ->then(function(Ratchet\Client\WebSocket $conn) {
                      $conn->on('close', function($code = null, $reason = null) {
                      echo "Connection closed ({$code} - {$reason})\n";
                  });

                  $conn->send('Hello World!');
                  $conn->close();
                }, function(\Exception $e) {
                  echo "Could not connect: {$e->getMessage()}\n";
                });
        });
        $loop->run();

1 个答案:

答案 0 :(得分:0)

嘿,ReactPHP核心团队成员在这里。因此,我从您的示例中注意到了几件事,这应该使调试起来更容易。

  • 我们的承诺有两种主要方法。 a)然后b)完成。然后可以链接并用于执行一系列返回诺言的操作。 done不能并且也被认为是链的末端,当引发错误但未在链中处理时,done将会追溯错误。您的代码中有一些更改,但有一些错误,但是可抛出异常被吞下了。
  • 建议不要在事件循环中运行while循环,因为它将阻塞循环以及内部运行的其他操作。 (使用sleep时也是如此,您可以使用计时器再等一秒钟。)
  • 您似乎正在为每条消息打开一个连接,打开单个连接并通过该连接将每条新消息推送到websocket服务器会更有效吗?