Search code examples
phplaravelratchet

Ratchet with laravel


I am planning to create an instant messaging service using Ratchet and laravel(I found a project called latchet, which integrates Ratchet into laravel)

My question is.

  1. How to verify a client before allowing him to start a web socket connection.
  2. One user can be part of multiple groups, so I want to create channels like Poll_grp_id , and get a list of all of a user's groups, and then subscribe to all those Poll_Grp_id channels. I am not sure about how to go about doing this

Solution

  • To answer your first question:

    public function onSubscribe(ConnectionInterface $conn, $topic, $userKey) {
        //check if the userKey is correct for that user, ...
    }
    

    I use this myself with an APIKey, and each time a user subscribes, they send the $userKey object with it.

    That object contains only the userId, apiKey, ...(whatever you need to verify the user)

    The second question:

    //code from socketo.me to give an example

    protected $subscribedTopics = array();
    
    public function onSubscribe(ConnectionInterface $conn, $topic) {
        $this->subscribedTopics[$topic->getId()] = $topic;
    }
    
    /**
     * @param string JSON'ified string we'll receive from ZeroMQ
     */
    public function onBlogEntry($entry) {
        $entryData = json_decode($entry, true);
    
        // If the lookup topic object isn't set there is no one to publish to
        if (!array_key_exists($entryData['category'], $this->subscribedTopics)) {
            return;
        }
    
        $topic = $this->subscribedTopics[$entryData['category']];
    
        // re-send the data to all the clients subscribed to that category
        $topic->broadcast($entryData);
    }
    

    In this you would change the onSubscribe($conn, $topic) to onSubscribe($conn, $topicArray)

    Afterwards you get all seperate 'channels' from that array and add them to the $subscribedTopics

    When you try to send something to those 'channels'/'topics', It will then send it to all connected clients that had the particular channel in their $topicArray

    I hope this helps.