I’ve created a simple chat application using PHP and the Ratchet library for WebSockets. However, I’m experiencing an issue when trying to connect to the server. The error message I receive is:
WebSocket connection to ‘wss://mywebsite.com:8080/’ failed.
I have already installed an SSL certificate on my website.
Could someone please help me troubleshoot this issue? Are there any common reasons for WebSocket connection failures, and how can I resolve this problem?
Thank you!
server.php
<?php
require 'vendor/autoload.php'; // Load Autoload
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
use RatchetHttpHttpServer;
use RatchetServerIoServer;
use RatchetWebSocketWsServer;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new SplObjectStorage; // Store all active connections
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
// Don't send the message to the sender
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// Detach the connection
$this->clients->detach($conn);
}
public function onError(ConnectionInterface $conn, Exception $e) {
$conn->close();
}
}
$server = RatchetserverIoServer::factory(
new RatchetHttpHttpServer(
new RatchetConnectionInterface(new Chat())
),
8080 // Choose a port
);
$server->run();
chat.php
<!DOCTYPE html>
<html>
<head>
<title>Chat Room</title>
<style>
body { font-family: Arial, sans-serif; }
#messages { border: 1px solid #000; height: 300px; overflow-y: scroll; }
#input { width: calc(100% - 22px); }
</style>
</head>
<body>
<h2>Chat Room</h2>
<div id="messages"></div>
<input type="text" id="input" placeholder="Type your message here..." />
<script>
var conn = new WebSocket('wss://mywebsite.com:8080');
conn.onmessage = function(e) {
var messagesDiv = document.getElementById('messages');
messagesDiv.innerHTML += '<div>' + e.data + '</div>';
messagesDiv.scrollTop = messagesDiv.scrollHeight;
};
document.getElementById('input').addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
conn.send(this.value);
this.value = '';
}
});
</script>
</body>
</html>
4