JDare / ClankBundle

A Symfony2 Bundle for use with Ratchet WebSocket Server
MIT License
131 stars 31 forks source link

Broadcast from eventlistener to topic #22

Closed npinon closed 9 years ago

npinon commented 10 years ago

Hi,

Is it possible to broadcast something to a topic from a custom Event Listener Class. I can't find the way to do it :/

Exemple : I want to broadcast a message when a client is disconnected.

Thx

alcalyn commented 10 years ago

You just have to create your topic class, and implement onUnSubscribe:

    /**
     * This will receive any UnSubscription requests for this topic.
     *
     * @param \Ratchet\ConnectionInterface $conn
     * @param $topic
     * @return void
     */
    public function onUnSubscribe(Conn $conn, $topic)
    {
        //this will broadcast the message to ALL subscribers of this topic.
        $topic->broadcast($conn->resourceId . " has left " . $topic->getId());
    }

See documentation: https://github.com/JDare/ClankBundle/blob/master/Resources/docs/TopicSetup.md

Edit: Ok but that is not triggered when an user leave the page. I am searching for a solution, the best should be to auto unsuscribe to all topic when user disconnect.

For now you still can unsuscribe from javascript when user leave page, by using onbeforeunload event:

window.onbeforeunload = function() {
    clankSession.unsubscribe('chat/my/topic');
};
npinon commented 9 years ago

It (solution with window.onbeforeunload) works! Thank you :smiley: It's not pretty clean code but it's better than nothing