I try to make a simple chat page on my symfony project by WebSocket. First I used React-php library, it perfectly works on terminal but when I try to connect it to browser I faced this error on chrome:
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
and on firefox
Firefox can't establish a connection to the server at ws://localhost:8000/.
Next I used Ratchet library and follow the tutorial but still the same problem, work on terminal, error on browser.
I use telnet localhost 8000
on terminal and javascript on browser is
var conn = new WebSocket('ws://localhost:8000');
conn.onmessage = function(e) {
console.log(e.data);
};
conn.send('Hello World!');
the server code for React
require __DIR__.'/../vendor/autoload.php';
$loop = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);
$conns = new \SplObjectStorage();
$socket->on('connection', function ($conn) use ($conns) {
$conns->attach($conn);
$conn->on('data', function ($data) use ($conns, $conn) {
foreach ($conns as $current) {
if ($conn === $current) {
continue;
}
$current->write($data);
}
});
$conn->on('end', function () use ($conns, $conn) {
$conns->detach($conn);
});
});
$socket->listen(8000);
$loop->run();
and server code for Ratchet
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/chat.php';
use Ratchet\Server\IoServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
$server = IoServer::factory( new WsServer( new Chat() ), 8000);
$server->run();
Another thing is client page url is localhost/X/chat
and server localhost/X/server
, I tried ws://localhost:8000/X/server
but still doesn't work