我必须在发送消息之间做一些复杂的计算,但是第一个消息是在计算后发送的。我怎样才能立即寄出呢?
<?php
namespace AppBundleWSServer;
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
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 computing
sleep(10);
//send result
$connection->send('{"command":"someString","data":"data"}');
return;
}
}
开始服务器:$server = IoServer::factory(
new HttpServer(
new WsServer(
$ws_manager
)
), $port
);
send
最终进入React的EventLoop,当它"就绪"时异步发送消息。同时,它放弃执行,然后脚本执行您的计算。完成这些操作后,缓冲区将发送第一条和第二条消息。为了避免这种情况,你可以在当前缓冲区耗尽后告诉计算在EventLoop上执行:
class CommandMessage implements RatchetMessageComponentInterface {
private $loop;
public function __construct(ReactEventLoopLoopInterface $loop) {
$this->loop = $loop;
}
public function onMessage(RatchetConnectionInterface $conn, $msg) {
$conn->send('{"command":"someString","data":"data"}');
$this->loop->nextTick(function() use ($conn) {
sleep(10);
$conn->send('{"command":"someString","data":"data"}');
});
}
}
$loop = ReactEventLoopFactory::create();
$socket = new ReactSocketServer($loop);
$socket->listen($port, '0.0.0.0');
$server = new RatchetIoServer(
new HttpServer(
new WsServer(
new CommandManager($loop)
)
),
$socket,
$loop
);
$server->run();