如何在 reactphp 上自动重新连接客户端?

How to reconnect a client automatically on reactphp?

我正在使用 reactphp 为 api 服务器创建客户端。但是我有一个问题,当我的连接关闭时,无论什么原因,我都无法自动重新连接。

没用:

$this->loop = \React\EventLoop\Factory::create();
$host = config('app.reactphp_receiver_host');
$port = config('app.reactphp_receiver_port');

$this->connector = new \React\Socket\Connector($this->loop);
$this->connector
     ->connect(sprintf('%s:%s', $host, $port))
     ->then(
           function (\React\Socket\ConnectionInterface $conn)
           {
              $conn->on('data', function($data)
              {

              });

              $conn->on('close', function()
              {
                   echo "close\n";
                   $this->loop->addTimer(4.0, function () {
                   $this->connector
                        ->connect('127.0.0.1:8061')
                        ->then( function (\Exception $e)
                        { 
                            echo $e;
                        });
                        });
               });
            });

$this->loop->run();

异常为空。

嗨,这里是 ReactPHP 团队成员。 Promise 的 then 方法接受两个可调用对象。第一个用于操作成功时,第二个用于发生错误时。看起来你在你的例子中混合了两者。我的建议是使用类似这样的东西来捕获错误和成功,但也可以无限地重新连接:

$this->loop = \React\EventLoop\Factory::create();

$this->connector = new \React\Socket\Connector($this->loop);

function connect()
{
  $host = config('app.reactphp_receiver_host');
  $port = config('app.reactphp_receiver_port');
  $this->connector
    ->connect(sprintf('%s:%s', $host, $port))
    ->then(
      function (\React\Socket\ConnectionInterface $conn) { 
        $conn->on('data', function($data) {
        });
        $conn->on('close', function() {
          echo "close\n";
          $this->loop->addTimer(4.0, function () {
            $this->connect();
          });
      }, function ($error) {
        echo (string)$error; // Replace with your way of handling errrors
      }
    );
}

$this->loop->run();