【问题标题】:How to reconnect a client automatically on reactphp?如何在reactphp上自动重新连接客户端?
【发布时间】:2018-09-17 05:54:32
【问题描述】:

我正在使用 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();

异常为空。

【问题讨论】:

    标签: php sockets client reactphp


    【解决方案1】:

    嗨,这里是 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();
    

    【讨论】:

    • 谢谢!有用。它ideone.com/kL1Ylw 也有效。我想做无限次重新连接,但客户端在 1 次重新连接后停止。我将“addTimer”替换为“addPeriodicTimer”。它不起作用。我该怎么做?
    • addPeriodicTimer 将继续每 4 秒调用一次 $this->connect();。此外,您可能希望将 $this->connect(); 添加到错误处理方法中(还添加一个 $conn->on('error' 处理程序),以便在错误时重新连接。
    • 是的!有用。谢谢你,WyriHaximus。我添加了:function (\React\Socket\ConnectionInterface $conn) { }, function ($error) { $this->reconnect(); }
    猜你喜欢
    • 2017-08-27
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 2012-07-24
    • 2010-09-17
    • 2019-09-12
    • 2020-12-10
    • 2019-11-20
    相关资源
    最近更新 更多