How to send messages to particular users Ratchet PHP Websocket

后端 未结 3 1751
庸人自扰
庸人自扰 2021-02-01 10:08

I\'m trying to build a system where user can subscribe to a category on establishing connection to websocket server and then he will start receiving updates for that category. S

3条回答
  •  半阙折子戏
    2021-02-01 10:31

    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.

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

    The javascript to go with that looks a bit like this

    
    

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

提交回复
热议问题