且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何向特定用户发送消息 Ratchet PHP Websocket

更新时间:2023-01-15 19:15:26

基本上,您需要一种将数据发送到 WebSocket 的语法,我建议使用 JSON 对象来执行此操作.在您的 WebSocket 类中,您需要一个名为 subscriptions 的局部变量和一个名为 users 的局部变量,就像这样.

Basically you want a syntax for sending data to the WebSocket, I reccomend using a JSON object to do this. In your WebSocket class you need a local variable called subscriptions and a local variable called users like so.

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface
{
    protected $clients;
    private $subscriptions;
    private $users;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
        $this->subscriptions = [];
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);
        switch ($data->command) {
            case "subscribe":
                $this->subscriptions[$conn->resourceId] = $data->channel;
                break;
            case "message":
                if (isset($this->subscriptions[$conn->resourceId])) {
                    $target = $this->subscriptions[$conn->resourceId];
                    foreach ($this->subscriptions as $id=>$channel) {
                        if ($channel == $target && $id != $conn->resourceId) {
                            $this->users[$id]->send($data->message);
                        }
                    }
                }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        unset($this->users[$conn->resourceId]);
        unset($this->subscriptions[$conn->resourceId]);
    }

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

要使用的 javascript 看起来有点像这样

The javascript to go with that looks a bit like this

<script type="text/javascript">
var conn = new WebSocket('ws://localhost:8080');

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

conn.onmessage = function(e) {
  console.log(e.data);
};

function subscribe(channel) {
    conn.send(JSON.stringify({command: "subscribe", channel: channel}));
}

function sendMessage(msg) {
    conn.send(JSON.stringify({command: "message", message: msg}));
}
</script>

注意:此代码未经测试,是我根据使用 Ratchet 的经验即时编写的.祝你好运:)

Note: This code is untested I wrote it on the fly from my experience with Ratchet. Good luck :)