首页 > 解决方案 > 从聊天类内部访问 Ratchet 循环

问题描述

我正在尝试使用 Ratchet 已经制作的事件循环。

$server=IoServer::factory(new HttpServer(new WsServer(new class implements MessageComponentInterface{
    public function __construct(){
        // get the Ratchet Loop
    }

    public function onOpen(ConnectionInterface $conn){}
    
    public function onMessage(ConnectionInterface $from, $msg){}
    
    public function onClose(ConnectionInterface $conn){}

    public function onError(ConnectionInterface $conn, \Exception $e){}
})),123);

我可以通过调用 $server->loop 来获取它,但是我无法将它传递给类构造函数,因为 $server 在自身初始化期间不可访问,我想知道是否有更好的获取方法?

标签: phpratchetreactphp

解决方案


您可以实例化一个循环并将其传递给__construct

$loop    = React\EventLoop\Factory::create();
$webSock = new React\Socket\Server('127.0.0.1:8080', $loop);

$server = new IoServer(new HttpServer(new WsServer(new class($loop) implements MessageComponentInterface {
    protected $loop;

    public function __construct(\React\EventLoop\LoopInterface $loop)
    {
        $this->loop = $loop;
    }

    public function onOpen(ConnectionInterface $conn)
    {
    }

    public function onMessage(ConnectionInterface $from, $msg)
    {
    }

    public function onClose(ConnectionInterface $conn)
    {
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
    }
})), $webSock);
$loop->run();

在这种方法中不能使用IoServer::factory. 因为您需要将自己的循环传递给$webSockandIoServer


推荐阅读