Let's say I'm making a chat, is it possible to sent messages to specific users and particularly groups of users? Can I hook up ID's to clients that have been logged on and groups that have been started, so I can sent messages to the server using these ID's and the server just sends these messages to the correct people? The chat app would look much like a chat from an MMO game where you can receive broadcast (from entire network), room, private, group and party messages in the same window.
Also I have a database behind this, is it possible I can use this for the above? Like using the same user ID's as in the database? Likewise I'm storing groups with an ID.
You can create rooms or even private chats using web sockets, there are lots of examples out there. I have only used Socket.IO and they are finally 1.0 production ready. Check their docs: http://socket.io/docs/rooms-and-namespaces/
// Join
io.on('connection', function(socket){
socket.join('some room');
});
// Emit
io.to('some room').emit('some event'):
Related
I'm trying to implement a communication method between client and admin (bidirectional) using Paho MQTT JS + Mosquitto broker 1.6.8 and I'm having some trouble with retained messages and persistent sessions.
What I want to accomplish:
My web client is subscribed to a topic where the admin publishes (let's say topicA) and the admin is subscribed to a topic where the client publishes (topicB). When any of the users received a message for that topic, it appears on the screen, and they keep appearing below the previous so that they form a list of messages. When they are both online, they have to see the messages that are being sent and if they go offline, they have to see the old and new messages as well. Also, the users must have the ability to clear the list of messages.
What I've tried so far:
My first try was setting the published messages with the retained value to true, so that the message can be delivered to future subscribers. However, I see that only the last message is retained. I investigated and found that I can establish a persistent session (by cleanSession: false) between broker and client, so that if I set the qos of the message to a value greater than 0 (0 or 1) and the client is subscribed to the topic, they'll get all the undelivered messages. This doesn't work for me, or at least the way I expect it to work. I've tried removing the Mosquitto Db and restarting (didn't change anything). I also tried using the same id for all clients and another id for all admins, because I thought that maybe, the broker saves the messages only for a particular clientID, so if a client with a completely different ID connects, they won't get the messages.
Is there a way of delivering ALL the undelivered messages (because of one client being online and the admin offline, or viceversa) and not only the las one (retained)? Or is there a way of retaining more than one message (better in my opinion, if I could clear the retained ones by sending a null payload) ?
First every client must have a unique client id. When there is a client id clash the oldest connected client will be disconnected.
Second it's the QoS of the subscription, not the publish that dictates if the broker will queue a message for a offline client with a persistent session
So for a client to receive messages published while it is offline, it must
Have previously connected and subscribed to the topic with a QoS of 1 or 2
When reconnecting it must use the same client id as last time
Have cleansession set to false
The messages will only be delivered once so there is no need to clear the messages, but if you don't have to receive the queued messages, set the cleansession flash to true.
The broker will only retain the last message published on a given topic that had the retained bit set, there is no way to change this.
We are using Tokbox to implement a set of pre-defined chat rooms.
Each room has a moderator and a specific group of users who can join the chat room only when the moderator has activated the chat room.
This has gone very well and quite smoothly.
My question is: How could we set up say a "super user" so that they may terminate any active chat session that might be going on? This superuser is not necessarily an active participant in any room. But, we would like to set up some sort of admin page where there is a button for each room that says "emergency terminate" or something like that.
We have database roles and user setup. We are just trying to figure out the best approach to do this with the Tokbox API.
TokBox Developer Evangelist here.
A client connected to a session with a moderator token can disconnect other connected clients in that session.
There is no concept of "super user", but you can use the use the OpenTok REST API to force disconnect connected clients from any session. You can also use the OpenTok PHP SDK to accomplish this.
use OpenTok\OpenTok;
$opentok = new OpenTok($apiKey, $apiSecret);
$sessionId = ""; // the session the client is connected to
$connectionId = ""; // this connection Id of client you want to force disconnect
$opentok->forceDisconnect($sessionId, $connectionId);
As you can see, you would need to know the connectionId of the client that you want to disconnect. The connectionId is part of the Connection Event that is dispatched with connectionCreated and connectionDestroyed events on the client side. You can also use Session Monitoring to receive these connection events via a webhook on your server.
I'm working on a pretty fun web app project that can become rather big, and I have a chance to play around with this handy thing called PubNub as main real-time engine of application.
So it's a web application with Node.js backend, involves potentially huge amount of chat rooms between users and realtime notifications sent to users by backend when some data in DB is updated.
Usually, developing with Sockets.io, I will just subscribe each user to channel of his unique DB id, and also to chanels representing different chat rooms.
This way I can handle chat rooms and authentication on backend and after storing some personal notification in DB I can easily push them to channel named by user id, so if user is online - he gets it, if not - fine, he will see it on next login, notification is already in DB. And theoretically this monstrocity should scale just fine horizontally with help of redis pub/sub.
Thing that worries me about PubNub in this case is scalability. As I obviously have no insight on what is going on in PubNub backend's dark corners, I want to make sure that app is built in the way that it will be prepared to handle some obscure enormously huge amount of simultaneous users.
My question is, what is the best approach to building such a system with PubNub?
Am I correct assuming that it will be better, in need of pushing notification to specific user, to subscribe to this user's pubnub, push note and unsubscribe. As if I will keep all online-user channels open - then there is no point in PubNub instead of websockets on my server, as server will be anyway under load of all of those opened online-user channels and should be scaled just to maintain huge quantity of them.
What about user authorisation? Without involving my backend how can I be sure that user posting some message will not be able to fake his personality and will have exatly the same as he have authenticated inside application?
And generally (and via PubNub) what is the best practice to tackle huge amounts of chats per users? As say during application life each user may accumulate some decent amount of garbage chat rooms that have some users in it, though havn't been touched by anyone for a long time, and users just way too lazy to leave it manually?
Thanks for Your patience in reading this wall of text!
UPDATED Dec 5, 2021
If you are implementing a chat app, please refer to the PubNub Chat use-case documentation for full details. It has new features and UI components that are built upon the PubNub Platform.
UPDATED May 15, 2020
We have some new docs that will explain much of the below in much clearer terms.
And new features that can be applied to many of the questions/answers below:
Message Actions
Message Counts
Batch History (multi-channel message fetch)
Objects (Users, Channels and Memberships Metadata)
NOTE: I've sprinkled some of the above links down in the answers below.
First, let's address this...
Thing that worries me about PubNub, in this case, is scalability. As I
obviously have no insight on what is going on in PubNub backend's dark
corners, I want to make sure that the app is built in a way that it will
be prepared to handle some obscure enormously huge amount of
simultaneous users.
and this...
then there is no point in PubNub instead of WebSockets on my server,
as the server will be anyway under the load of all of those opened online-user
channels and should be scaled just to maintain the huge quantity of them
This is sort of backward because you would use a service like PubNub to ensure that your application scales to handle millions of users. PubNub has thousands of customers that scale to millions of users and 100's of billions of messages. Not knowing how PubNub does this frees you to implement the biz logic of your application.
But I think I get what you are saying. You are under the impression that your server has to be involved in each and every chat room interaction for every user, but that is only partially true. Mostly, your server will be used for authentication, some subscription maintenance (optional), and probably for sending messages out to one, many, or all end users, as required (depends on your requirements).
Here are some attempts to answer your questions although they are kind of a bit all over the place so I will do my best to answer what I think it is you are asking.
Question 1
This question seems to be directed at maintaining lots of subscriptions to channels and the scalability of that.
Generally speaking, every end-user initializes PubNub and subscribes to channels they need to listen to and publish to channels they need to send messages on. Typically, the channels (chat rooms in your case, I assume) they are publishing on are the same channels they are subscribing to, but they are different kinds of use cases. And you can subscribe to thousands of channels at a time (up to 20K per client). If you did this with WebSockets, how would you go about scaling this to millions of users? You would implement and operate (to scale) something similar to PubNub (not easy and not cheap).
Now, if a user is subscribed to a bunch of chat room channels but some or many are stale (user hasn't viewed or posted to in a while), you could have some code on your server (or the client) that monitors the activity of users and unsubscribes them from those stale channels. This is possible using channels groups. Each end-user would have their own channel group that contains all the channels they are listening to. And the client code or the server code and add and remove channels to/from those end users' channel groups.
Question 2
UPDATED DOCS: https://www.pubnub.com/docs/platform/security/access-control
Now this question is a bit more clear and focused and is asking about authentication (login) and how to ensure someone is who they say they are and how to handle authorization (what they can and cannot do) and where/who controls this.
The answer is, you control the authentication (login) to prove that the person is what they say they are. Your log-in process checks for a valid username/password and in the user record, you will have a list of access controls for that user. With that, you generate an auth-key that you grant read and/or write access to one or more channels. This grant is a PubNub operation that your server invokes. The auth-key is passed back to the client and the client code initializes PubNub instance using the pub/sub keys and this auth-key that PubNub servers use to check for access based on the channel and the operation being requested (subscribe to this channel, publish to that channel, etc). If the auth-key does not have the proper access, the PubNub server will deny access (403 response).
There's more to all of this but this is a good start. Read up on PubNub Access Manager for the SDK you will be using on our docs page. For example, you can start with the JavaScript SDK Access Manager docs and tutorials.
Question 3
UPDATED DOCS: https://www.pubnub.com/docs/platform/channels/receive#subscribe-to-channels
I believe I answered this sufficiently with question 1 - Channel Groups. Start with the JavaScript SDK Stream Controller (which provides Channel Group feature) docs and tutorials.
I hope I have managed to move you a few steps further along your journey to a highly successful real-time, data stream application using PubNub. Please reply with any additional questions you may still have.
*Answers to your new comments:*
Thanks for your follow-up comments. It is very clear what you are asking now.
I will need to compare chat room timestamp with personal user last-read timestamp for this, so it seems that I need to listen to those channels from back-end and update user's last-reads, or to trust into the front-end, and get timestamps from a user directly
No, you do not have to listen to the channels on your server. Yes, from the client app, you will keep the timestamp of the last received message. When the user comes back online, you use this timestamp to get history for the channels the client was subscribed to. Many have done this successfully and we are going to be releasing some amazing features in the coming months that will simplify this considerably.
pushing real-time notifications to users from the back-end. Do I need to be subscribed to all of my user channels if I want to push notes to them at any time?
You can publish on any channel without actually subscribing to it first. So your server can publish to channels as it needs to.
And as before, keep coming with more questions as you require.
*Great follow-up questions again. Here's what I suggest*
... it makes sense to not request all of those chat rooms from DB and join via pubnub all of them, but rather implement pagination... how user can be aware of new messages that may appear in his old chat rooms?
Again, you can stay subscribed to 20K channels using channel groups. You can subscribe to 10 channel groups with 2K channels per channel group - but I'd recommend just limiting the user to 100 or less because that seems like a sufficient limit to impose in your app. But pick whatever upper limit you want and when the user hits that limit, force them to leave another chat room first or suggest they leave one of the top 10 most inactive, or some algorithm that makes sense for your app.
UPDATED DOCS: https://www.pubnub.com/docs/platform/channels/receive#subscribe-to-channels
Getting the # of missed messages does require a full history fetch, but we are going to be providing improved APIs to make this simpler in the near future. But if the user is registered for push notifications on all these channels, the device would be able to receive these push messages and your app can keep that count locally. We will have a "how to update the badge count in background" article being published soon. You could also use that to keep track of the number of missed messages per channel (chat room).
For now I just want to limit the number of rooms available for users to let's say a hundred and request and join them without pagination.
UPDATED DOCS: https://www.pubnub.com/docs/platform/channels/retrieve
We do have customers that do this without worrying about pagination. They just retrieve history on the 100 channels the device is subscribed to. With the background badge count updater strategy, you will have the advantage to know which channels to fetch from when the app becomes active. I will post the link to that article here once it is published.
Im making a simple chat app that sends messages through a redis pub/sub channel. I do not use any login options just lets the user select a username and chat. I am trying to implement private chat where one client is able to communicate to another connect client. I am new to chat client programming, I am trying to figure out how to communicate with only one client. What are some options I could consider to get the ability to chat 1 on 1? I don't mind changing my architecture to incorporate a new tool. Any suggestions is appreciated
I did something similar with raw sockets. I held user objects which contained the connected socket, the name, and whether they are chatting. If a user is not in chat he can type a command /list users which gives the list of users currently connected. When he has found someone to chat with he enters the command /chat bob. If the user bob is already chatting he will receive a message from the server saying that bob is in a chat already. Otherwise a chat session will be established between the two users. They now will be in chat until one of them enters /endchat. Then they will be able to find new people to chat with.
The trick is implementing the server so it can track a list of users and their chatting status and who they are in chat with so when ever they type /endchat the other user can be notified.
The combination of Nodejs + Socket.io would solve your problem i suppose. Specifically rooms functionality is what you are looking for here.
Lets say you have two users bob and gob. Considering both are online (although you can add Redis as a session store and for storing history later, which i did in my case). Say bob wants to chat with gob he selects gob. Now make bob join a room using
var roomname = 'bob'>'gob'?'bob'+'gob':'gob'+'bob' ;
//this type of naming ensures roomname is same for both users
socket.join(roomname);
This will work only if both have chosen each other. So now when gob selects bob both are joined in the same room. Whenever someone sends a message make them emit to that room using
socket.broadcast.to(roomname).emit('message_event',msgObj);
Make sure you have have added the listener
socket.on('message_event',messageHandler);
When chat is finished make them leave the room using
socket.leave(roomname);
I am trying build a chat server using MEAN Stack (not using redis), which uses socket.io for enabling real time chat. For private messaging, I want to implement the built-in "room" feature of socket.io. The flow goes as follows :
User1 wants to start a conversation with User2, so User1 emits an event, which the server catches.
In the server, I store this conversation in database and join User1 to a room. If User2 is online, then I join User2 also to this room. For achieving this step, I need access to the socket of User2.
After a good amount of research, I found this method to store the "socket" of every connected user in an array(or dictionary).
I was wondering if there is any other method to retrieve the socket other than storing it in an array.
No, no better way, except if you use different namespace for the two users, but i don't think it's your case.
I implemented a basic POC (proof of concept) a couple years ago using faye.
In my case I created a unique channel for active users. The channel name was the same as the unique user identifier from mongo ( _id ). This allowed me to send messages to the correct user without having to store information about their connection.
Please note that I did not do any performance testing and that you would need to have a lot of connections open.
I did a similar implementation using faye by broadcasting to channels, in that case I did store in the database who was connected to a specific channel.