Php 棘轮WebSocket-立即发送消息
我必须在发送消息之间进行一些复杂的计算,但第一条消息在计算后与第二条消息一起发送。我怎么能马上寄出去Php 棘轮WebSocket-立即发送消息,php,websocket,ratchet,Php,Websocket,Ratchet,我必须在发送消息之间进行一些复杂的计算,但第一条消息在计算后与第二条消息一起发送。我怎么能马上寄出去 <?php namespace AppBundle\WSServer; use Ratchet\MessageComponentInterface; use Ratchet\ConnectionInterface; class CommandManager implements MessageComponentInterface { public function onOp
<?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;
}
}
send
最终会通过React的EventLoop实现,该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();
您可以使用每毫秒运行一次的EventLoop,以及您自己要发送的消息队列。这是一个好主意,但我认为这不是最佳解决方案(大量迭代,什么都不做)。不幸的是,我不知道有什么更好的办法。是的,这是一种万不得已的建议。缺少对棘轮核心部件的过度使用。我想你可以用symphony来启动一个新的流程来做计算工作?
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();