I have got a Websocket server using Ratchet/PHP:
<?php
require __DIR__.'/../vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Mediator;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Mediator()
)
),
9000
);
$server->run();
?>
Mediator class:
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Mediator implements MessageComponentInterface {
protected $clients = [];
public function onOpen(ConnectionInterface $conn) {
$this->clients[$conn->resourceId] = $conn;
echo "New connection! ({$conn->resourceId})
";
}
public function onMessage(ConnectionInterface $from, $msg) {
echo "Incoming: $msg
";
}
public function onClose(ConnectionInterface $conn) {
unset($this->clients[$conn->resourceId]);
echo "Connection {$conn->resourceId} has disconnected
";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}
";
$conn->close();
}
}
?>
Now on the client side, I have this basic JS code:
let ws = new WebSocket('wss://localhost:8443');
ws.addEventListener('open', () => {
ws.send('Hello!');
});
ws.addEventListener('message', event => {
alert(event.data);
});
It does work (I can send and receive messages), however here's the problem:
When visiting the page for the first time, a connection with the websocket server is established and works fine. When I close the page, the connection is closed (as it should). However, when I refresh the page the connection is closed (on unloading the page, this is normal) but when the page is loaded again, no connection is made to the websocket server. I have to refresh again to make the script connect. This should not happen, right? I have no idea why this is happening, what's causing this.