Red*_*tos 5 php websocket ratchet
我必须在发送消息之间进行一些复杂的计算,但是第一个消息在执行后以秒发送.我该如何立即发送?
<?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;
}
}
Run Code Online (Sandbox Code Playgroud)
启动服务器:
$server = IoServer::factory(
new HttpServer(
new WsServer(
$ws_manager
)
), $port
);
Run Code Online (Sandbox Code Playgroud)
小智 1
send最终进入 React 的 EventLoop,当消息“准备好”时,它会异步发送消息。同时它放弃执行,然后脚本执行您的计算。完成后,缓冲区将发送您的第一条和第二条消息。为了避免这种情况,您可以在当前缓冲区耗尽后告诉计算在 EventLoop 上执行:
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();
Run Code Online (Sandbox Code Playgroud)