gpt4 book ai didi

php - 如何在 ratchetphp 上自动重新连接客户端?

转载 作者:行者123 更新时间:2023-12-04 16:45:32 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com