【问题标题】:Ratchet WebSocket - send message immediatelyRatchet WebSocket - 立即发送消息
【发布时间】:2015-08-25 13:16:39
【问题描述】:

我必须在发送消息之间进行一些复杂的计算,但第一条消息是在计算后发送的第二条消息。我怎样才能立即发送?

<?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
);

【问题讨论】:

  • 您可以使用每毫秒运行一次的 EventLoop,以及您自己的要发送的消息队列。
  • 这是个好主意,但我认为这不是最佳解决方案(很多迭代,什么都不做)。不幸的是,我不知道任何更好的方法。
  • 是的,这是一种最后的建议。没有覆盖 Ratchet 的一些核心部分。我想你可以使用 symphony 来启动一个新的进程来做计算?

标签: php websocket ratchet


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    • 2023-01-09
    • 2017-05-31
    • 2011-11-16
    相关资源
    最近更新 更多