棘轮WebSocket - 立即发送消息

时间:2015-06-10 10:30:40

标签: 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;
    }
}

启动服务器:

$server = IoServer::factory(
              new HttpServer(
                  new WsServer(
                      $ws_manager
                  )
              ), $port
);

1 个答案:

答案 0 :(得分:1)

send最终会进入React的EventLoop,当它准备就绪时,它会异步发送消息&#34;。同时它放弃执行,然后脚本执行计算。到那时,缓冲区将发送您的第一条和第二条消息。为了避免这种情况,你可以告诉计算在当前缓冲区耗尽后在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();