首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在reactphp上自动重新连接客户端?

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

Stack Overflow用户
提问于 2018-04-07 09:11:20
回答 1查看 595关注 0票数 1

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

这不管用:

代码语言:javascript
复制
$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();

异常是空的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-04-07 14:40:11

嗨,ReactPHP团队成员。诺言的方法则接受两个可调用项。第一个用于操作成功时,第二个用于发生错误。看起来你在你的例子中把两者混合在一起。我的建议是使用这样的方法,捕捉错误和成功,但也可以无限地重新连接:

代码语言:javascript
复制
$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();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49705738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档