问题描述
我有一个用 Ratchet PHP 制作的聊天应用程序。这个应用程序就像一个魅力,除非我失去连接。对于我的测试,我将手机连接到应用程序并禁用 wifi 和 4G。我在文档中看到我需要使用 enableKeepAlive,它等待重新连接,但当用户在恢复互联网后尝试发送消息时,它永远不会重新连接或创建新连接。 有人可以解释我如何在不重新加载页面的情况下重新连接我的客户端?我不明白,搜索时什么也没找到。 PS:我把我认为重要的代码给你了,不会和你分享所有的代码,所以如果你不明白我的聊天是如何工作的,不要害怕:)
我的连接代码:
<?PHP
namespace MySite;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Connection implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onopen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function sendAll(ConnectionInterface $from,$msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n",$from->resourceId,$msg,$numRecv,$numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver,send to each client connected
$client->send($msg);
}
}
}
public function onMessage(ConnectionInterface $from,$msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s"' . "\n",$numRecv == 1 ? '' : 's');
$from->send($msg);
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed,remove it,as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn,\Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
我的 Ratchet 应用程序代码:
<?PHP
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MySite\Connection;
require dirname(__DIR__) . '/vendor/autoload.PHP';
$server = IoServer::factory(
new HttpServer(
$wsServer = new WsServer(
new Connection()
)
),8081
);
$wsServer->enableKeepAlive($server->loop,30);
$server->run();
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)