I have a chat application made with Ratchet PHP. This application work like a charm except when I loose my connection. For my test I connect my phone to the application and disable wifi and 4G. I see on the documentation that I need to use enableKeepAlive, it wait for reconnection but never reconnect or create a new connection when the user try to send a message after having internet back. Someone can explain me how to reconnect my client without reload the page ? I don't understand and doesn't found nothing when I search. PS : I put you the code I think important and don't share you all the code, so don't be afraid if you don't understand how work my chat :)
My connection code :
<?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"
, $from->resourceId, $msg, $numRecv, $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();
}
}
My Ratchet application code :
<?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();