I've been following the Hello World tutorial for a simple web chat with websockets on Ratchet, but I'm running into some problems. On Ubuntu when I run "php bin/chat-server.php" and it takes control of my command line just fine, but when loading index.html on Firefox I get
this in my console and on Chrome I get
this. When using telnet the chap works fine, it's just in the browser that it seems to not work. So what's wrong? Information on my problem is below.
I'm running LAMP on Ubuntu.
File Structurekingsconflict
websockets
index.html
composer.json
bin
chat-server.php
src
MyApp
Chat.php
vendor
autoload.php
cboden
composer
evenement
guzzle
react
symfony
chat-server.php<?php
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new WsServer(
new Chat()
)
, 8080
);
$server->run();
Chat.php<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat 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 onMessage(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 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();
}
}
index.html<html>
<body>
<script>
var conn = new WebSocket('ws://kingsconflict.net:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
conn.onerror = function(e) {
console.log("ERROR");
}
</script>
</body>
</html>
composer.json{
"autoload": {
"psr-0": {
"MyApp": "src"
}
},
"require": {
"cboden/Ratchet": "0.2.*"
}
}