作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 rachetphp 为 api 服务器创建客户端。但是我有一个问题,当我的连接关闭时,无论什么原因,我都无法自动重新连接。
这里是我使用的库:https://github.com/ratchetphp/Pawl
<?php
require __DIR__ . '/vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);
$connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
->then(function(Ratchet\Client\WebSocket $conn) {
$conn->on('message', function(\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "Received: {$msg}\n";
$conn->close();
});
$conn->on('close', function($code = null, $reason = null) {
echo "Connection closed ({$code} - {$reason})\n";
});
$conn->send('Hello World!');
}, function(\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
$loop->run();
我想在连接关闭后每隔几秒尝试重新连接一次。有什么想法吗?
最佳答案
这个想法很简单,但需要一些重构。我们必须将重新连接代码放在连接关闭时执行的处理程序中。为此,我们在 self 中传递了 $app
函数。
require __DIR__ . '/vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$connector = new Ratchet\Client\Connector($loop);
$app = function (Ratchet\Client\WebSocket $conn) use ($connector, $loop, &$app) {
$conn->on('message', function (\Ratchet\RFC6455\Messaging\MessageInterface $msg) use ($conn) {
echo "Received: {$msg}\n";
$conn->close();
});
$conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
echo "Connection closed ({$code} - {$reason})\n";
//in 3 seconds the app will reconnect
$loop->addTimer(3, function () use ($connector, $loop, $app) {
connectToServer($connector, $loop, $app);
});
});
$conn->send('Hello World!');
};
function connectToServer($connector, $loop, $app)
{
$connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])
->then($app, function (\Exception $e) use ($loop) {
echo "Could not connect: {$e->getMessage()}\n";
$loop->stop();
});
}
connectToServer($connector, $loop, $app);
$loop->run();
想法是,当连接接收到 close
事件时,我们使用 connectToServer
函数重新连接:
$conn->on('close', function ($code = null, $reason = null) use ($connector, $loop, $app) {
echo "Connection closed ({$code} - {$reason})\n";
//in 3 seconds the app will reconnect
$loop->addTimer(3, function () use ($connector, $loop, $app) {
connectToServer($connector, $loop, $app);
});
});
关于php - 如何在 ratchetphp 上自动重新连接客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43178554/
我是一名优秀的程序员,十分优秀!