RatchetPHP无法在循环中向所有客户端发送消息

时间:2018-07-16 16:47:30

标签: php ratchet event-loop reactphp

我正在使用Ratchet PHP向客户端发送消息,并且正在使用

$server->loop->addPeriodicTimer(1, function () use ($row, $server) {...

每秒发送一条消息。我可以echo消息并且MySQL查询可以正常工作,但是我无法实际访问clients中的$server对象,我可以进入$server->app,但是当我然后执行->clients,它告诉我$clients不存在。

为澄清起见,当我不使用new HttpServer(...)时这不是问题,但是如果没有它,浏览器控制台会说websocket握手无效,所以这不是一个好的解决方法。

我已使用print_r($server),并确认clients对象在_httpServer:protected项内。我想,如果我可以访问它,我将能够发送消息。

实际服务器video-server.php的代码:

<?php
include "../../include/db.info.php";

use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use React\EventLoop\Factory;
use MyApp\Chat;

require dirname(__DIR__) . '/vendor/autoload.php';

$server = IoServer::factory(
                new HttpServer(
                new WsServer(
                new Chat()
                )
                ), 888
);

$pdo = new PDO("mysql:host=localhost;port=3306;dbname=erewhon", "root", "");

$getUsername = $pdo->prepare("SELECT * FROM messages WHERE id=201");
$getUsername->execute();

$row = $getUsername->fetch(PDO::FETCH_ASSOC);

$server->loop->addPeriodicTimer(1, function () use ($row, $server) {        
    /*foreach ($server->app->component->clients as $client) {                  
            $client->send("hello client");          
    }*/
    print_r($server->app);
});

$server->run();
?>

类文件chat.php的代码:

<?php
namespace MyApp;
header("Content-Type: application/json; charset=UTF-8");


//include "../../db.info.php";


use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {


    public $clients;

    public function __construct() {
        $this->clients = new \SplObjectStorage;
        echo "Congratulations! the server is now running\n";
    }

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {
        //dont need this
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }

}
?>

2 个答案:

答案 0 :(得分:0)

看来您无法以所需的方式获取该数据。 HttpServer定义一个受保护的变量。

protected $_httpServer; //<--- protected, you can't read from outside.
public function __construct(HttpServerInterface $component) {
    $this->_httpServer = $component;
    $this->_reqParser  = new HttpRequestParser;
}

但是,您可以传递Chat的实例并对其进行跟踪。它将指向相同的内存地址。

尝试一下:

$chat = new Chat(); //<--- ADD THIS LINE
$server = IoServer::factory(
            new HttpServer(
              new WsServer(
                $chat //<----- USE HERE
              )
            ), 888
          );

....

$server->loop->addPeriodicTimer(1, function () use ($row, $server, $chat) {        
    /*foreach ($server->app->component->clients as $client) {                  
        $client->send("hello client");          
    }*/
    print_r($server->app);
    print_r($chat->clients); // <---- PRINT HERE TO GET THE INFO
});

答案 1 :(得分:0)

为防万一,下面是我的原始答案,但我想强调一下,可接受的答案是正确的方法,只是不要忘记将其传递给use

我知道我可能不应该这样做来解决我的问题,但是它已经解决了,所以就足够了:

我去vendor\cboden\ratchet\src\Ratchet\Http并编辑了HttpServer.php,特别是变量protected $_httpServer,然后将其更改为public $_httpServer,我可能不应该这样做,但这解决了我的问题。

我可以通过执行clients来访问$server->app->_httpServer->component->clients项目。

感谢Felippe Duarte突出显示此属性,我没想到。