首页 > 解决方案 > 如何使用 Ratchet 从服务器 websocket 向特定客户端发送数据

问题描述

我是 Ratchet 和 websockets 的新手。

我想用 PHP、Javascript 和 Ratchet 创建一个实时应用程序。

我只需要将数据发送给正在使用该应用程序并拥有permissionId === 2.

这是我的代码服务器端:

namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface {
    protected $clients;
    //protected $customers;

    public function __construct() {
        echo 'The server is running' . "\n";
        $this->clients = new \SplObjectStorage;
        //$this->customers = [];
    }

    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) {

        require "../db/config.php";

        $numRecv = count($this->clients) - 1;
        echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
            , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');

        $query = "";

        $result_to_send = [];
        
        switch ($msg) {
            case "get_users":
                $query = "SELECT id, name, email FROM users where login_status = 1";
                break;
            case "get_provinces":
                $query = "SELECT prov_id, prov_nome FROM provincie where active = 1";
                break;
        }

        $result_query = mysqli_query($conn_db, $query);

        while($row = mysqli_fetch_assoc($result_query)) {
            $result_to_send[] = $row;
        }

        $result_message = array("action" => $msg, "data" => $result_to_send);

        foreach ($this->clients as $client) { //here I pass the data to everyone
                $client->send(json_encode($result_message)); 
        }
    }

    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();
    }
}

一切正常。唯一的问题是,在该方法中,onMessage我只想将查询结果发送给拥有 apermissionId === 2而不是所有人的客户端。

我想我必须在客户端改变一些东西:

    conn.onopen = function(e) { //passing variable permissionId
        console.log("Connection established!"); 
    };

我想我最后还必须onOpen在 PHP 的方法中做一些事情来捕获变量permissionId并将该变量与$conn->resourceId.

可以帮忙?

标签: javascriptphpratchet

解决方案


推荐阅读