harvey_slash harvey_slash - 1 year ago 98
PHP Question

Ratchet , get client's topics on connection close

I am using ratchet to enable push notifications for a group chat.

I have decided to do the following:

  • whenever a user connects,subscribe him to all the group topics that he part of along with a personal message topic.

I have an array
protected $subscribedTopics = array();
of topics as mentioned in ratchet's tutorial.

This will work, but over time , the number of group topics/user topics will only increase (there is no way to remove those topics from subscribed topics array).

By design, my app won't allow to send message from client to server, nor will it allow user to unsubscribe. It can only close the connection

So, I need a way to get all the topics that the user has subscribed to , when he closes(my logic is, if he is the only subscriber to some topics, remove those topics from the array of subscribed topics )

the onClose method is:

public function onClose(ConnectionInterface $conn) {
echo "close";

How can I do it ?

Answer Source

You still need to call unsubscribe from a topic once a connection is closed to entirely remove it from the websocket.

public function onClose(ConnectionInterface $conn) {
    foreach ($conn->Chat->rooms as $topic => $one) {
        $this->onUnSubscribe($conn, $topic);

Using this code you are able to unsubscribe from a $topic when the connection is closed.

and to make the unsubscribe working you will need something alike this:

function onUnSubscribe(ConnectionInterface $conn, $topic) {
    if ($this->rooms[$topic]->count() == 0) {
        unset($this->rooms[$topic], $this->roomLookup[array_search($topic, $this->roomLookup)]);
        $this->broadcast(static::CTRL_ROOMS, array($topic, 0));
    } else {
        $this->broadcast($topic, array('leftRoom', $conn->WAMP->sessionId));

This is just an applied sample to extend the tutorial, so that it can be used by others as well.

If you need any further help please let me know

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download