使用ReactPHP定期向Ratchet中的特定客户端发送消息

问题描述 投票:0回答:1

一般信息使用Ratchet PHP在聊天系统上工作。应用户的要求,我正在尝试在特定的聊天室中实现Triviabot。聊天室实际上并不“存在”。而是检查数组中列出了哪些客户端ID,并仅将消息发送给这些客户端。

想法是每x秒问一个问题。

问题实现ReactPHP定期计时器不是问题。这正在按预期方式工作。问题在于,一旦启用计时器,它就会阻止与websocket的任何连接。除了客户端说无法建立连接之外,没有其他错误。

相关代码

<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use React\EventLoop\Factory;

class Chat implements MessageComponentInterface {
    private $msgLoop;

    public function __construct() {
        $this->startTriviaBot();
    }

    private function startTriviaBot(){
        $this->msgLoop = Factory::create();

        $this->msgLoop->addPeriodicTimer(1, function (){

            // This is working as expected confirming the timer works fine
            echo 'test'.PHP_EOL;

            foreach($this->clientIDsPerRoom['trivia'] as $receiverID){
                if(array_key_exists($receiverID, $this->userObjects)){

                    $this->sendMessage('Trivia', 'trivia', 'Bot test message', $receiverID);
                }
            }
        });

        // Commenting this makes the websocket accept connections again
        $this->msgLoop->run();
    }
}

我完成的研究没有帮助

Periodically sending messages to clients in Ratchet-这是直接从创建网络套接字而不是在MessageComponentInterface内向所有客户端发送消息。它无权访问特定的客户端。

[Create a timer with Ratchet php-这基本上是我正在做的,但它正在引起我遇到的问题。

php timer ratchet reactphp
1个回答
1
投票

嘿ReactPHP核心团队在这里。看起来您正在创建一个新的循环来运行计时器。实际上,这将停止您创建用来启动Ratchet的初始事件循环。您还需要将为Ratchet创建的事件循环传递给此类,并使用该循环。只能有一个事件循环。 (如果您没有将事件循环传递给Ratchet,它将为您创建一个并使用它。将一个传递给Ratchet将覆盖该行为。)

© www.soinside.com 2019 - 2024. All rights reserved.