Ratchet: Still Connected State

I'm starting about this websocket, and I'm trying to use this Ratchet for my first project.

I did an installation tutorial at http://socketo.me by running this command on the command line

composer require cboden/ratchet

after that it automatically creates a vendor folder with a couple of libaries there and on the home path a composer.json and composer.lock

Then I made a chat.php file and copied the code from a quick example with the git ratchet mechanism, which:

 <?php use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; // Make sure composer dependencies have been installed require __DIR__ . '/vendor/autoload.php'; /** * chat.php * Send any incoming messages to all connected clients (except sender) */ class MyChat implements MessageComponentInterface { protected $clients; public function __construct() { $this->clients = new \SplObjectStorage; } public function onOpen(ConnectionInterface $conn) { $this->clients->attach($conn); } public function onMessage(ConnectionInterface $from, $msg) { foreach ($this->clients as $client) { if ($from != $client) { $client->send($msg); } } } public function onClose(ConnectionInterface $conn) { $this->clients->detach($conn); } public function onError(ConnectionInterface $conn, \Exception $e) { $conn->close(); } } // Run the server application through the WebSocket protocol on port 8080 $app = new Ratchet\App('localhost', 8080); $app->route('/chat', new MyChat); $app->route('/echo', new Ratchet\Server\EchoServer, array('*')); $app->run(); 

Then I run this command on the command line: php chat.php

I still have an error in my client side:

Chrome Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

Firefox InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

My folder (on XAMPP):

Client

htdocs/public/chat/index.php with common.js intact, containing

 var conn = new WebSocket('ws://localhost:8080/echo'); conn.onmessage = function(e) { console.log(e.data); }; conn.send('Hello Me!'); 

Server

 htdocs/public/chatserver/chat.php htdocs/public/chatserver/vendor/<some libraries> htdocs/public/chatserver/composer.json htdocs/public/chatserver/composer.lock 

Did I miss something?

+5
source share
1 answer

try the following:

 var conn = new WebSocket('ws://localhost:8080/echo'); conn.onmessage = function(e) { console.log(e.data); }; conn.onopen = function(e) { console.log("Connection established!"); conn.send('Hello Me!'); }; 

You should be able to send when the connection is open. It seems like you are trying to do this before establishing a connection.

+9
source

Source: https://habr.com/ru/post/1215502/


All Articles