Question

In my chat room there can be multiple moderators in a room at same time. Every moderator can open/close room from public at any time. If a room is closed, no new members can access it, no need to care for those who are already in.

So a question, how do I correctly sync the chatroom open / closed status?

I was using a special moderator channel, every moderator page kept publishing it's state to it, and also was subscribed to it.

It works most of the time, but I believe there can be a sync issue, when I publish Closed state, and then get Open state from another moderator who hasn't yet received my publish update.

Was it helpful?

Solution

PubNub State Sync for Multiple Chat Clients

One good way to handle this situation is use the PubNub Storage & Playback Service for Data Management and Message State. Specifically the PUBNUB.history({...}) API call. You can create a "chatroom_status" channel for every chat room (i.e. "chatroom_a_status", "chatroom_b_status").

Note: are you creating a unique moderator channel for each chat room, or a shared moderator channel? If the former, then the "chatroom_status_n" example above is basically the same thing.

Before the moderator changes the state of a chatroom, he can just call PUBNUB.history({...}) on the "chatroom_n_status" channel to retrieve the last known state of the chatroom. If the status is "closed" the moderator will know another moderator closed the chat room (and if you pass the moderator ID, you could also track which moderator closed the channel).

You will be able to achieve State sync for chat may be accomplished by using PubNub Storage & Playback Service for Data Management.

Here is some example code for simple state management:

// Init PubNub
var pubnub = PUBNUB({ publish_key : 'demo', subscribe_key : 'demo' });

// Get State of Chat Room
function get_state( chat_room, callback ) {
    pubnub.history({
         channel : chat_room + '-state',
        callback : function(msgs) { callback(msgs[0][0] || default_state) }
    });
}

// Set State of Chat Room
function set_state( chat_room, state ) {
    pubnub.publish({ channel : chat_room + '-state', message : state });
}

And you can use this like:

set_state( 'chatroom_a', { open : true } );
get_state( 'chatroom_a', function(state) { console.log(state) } );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top