Ratchet WebSocket - send a message immediately

I need to do some complicated calculations between sending messages, but the first message is sent with the second after compulting. How can I send it immediately?

<?php namespace AppBundle\WSServer; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class CommandManager implements MessageComponentInterface { public function onOpen(ConnectionInterface $conn) { //... } public function onClose(ConnectionInterface $connection) { //... } public function onMessage(ConnectionInterface $connection, $msg) { //... $connection->send('{"command":"someString","data":"data"}'); //...complicated compulting sleep(10); //send result $connection->send('{"command":"someString","data":"data"}'); return; } } 

Start Server:

 $server = IoServer::factory( new HttpServer( new WsServer( $ws_manager ) ), $port ); 
+5
source share
1 answer

send eventually makes its way to the React EventLoop, which sends the message asynchronously when it is ready. At the same time, it refuses to execute, and then the scripts perform your calculation. When this is done, the buffer will send your first and second messages. To avoid this, you can say that the calculation should be performed on the EventLoop as a check mark after the current buffers are merged:

 class CommandMessage implements \Ratchet\MessageComponentInterface { private $loop; public function __construct(\React\EventLoop\LoopInterface $loop) { $this->loop = $loop; } public function onMessage(\Ratchet\ConnectionInterface $conn, $msg) { $conn->send('{"command":"someString","data":"data"}'); $this->loop->nextTick(function() use ($conn) { sleep(10); $conn->send('{"command":"someString","data":"data"}'); }); } } $loop = \React\EventLoop\Factory::create(); $socket = new \React\Socket\Server($loop); $socket->listen($port, '0.0.0.0'); $server = new \Ratchet\IoServer( new HttpServer( new WsServer( new CommandManager($loop) ) ), $socket, $loop ); $server->run(); 
+1
source

All Articles