简体   繁体   中英

Send updates to a user using Socket.io and nodejs

I'm building an app using MEAN Stack (something like Facebook). So a user can login to my app using different browsers and I want for example, if there user will add a new message to the MongoDB, I want to update his messages in the other sessions. The same of he will remove a massage. At the same time, there maybe logged in different users from different browsers and I want to notify the user with his update in the other sessions.

Does Socket.io supports such an option? And what is the best way to do it?

Thanks.

Yes socket.io do support that. Here is an example made by socket.io themselves: https://github.com/socketio/socket.io/tree/master/examples/chat

You should be looking for socket.on() which are the listeners for an event on the server side and look into socket.emit() which are the senders of the events. the .emit() could be added into an function which are triggered on a button click for example.

Depending on you needs, if you're going to send the message to every user using your app then you could use this above code. But if you only wants to send to a specific list of persons you should look into something called Rooms ( http://socket.io/docs/rooms-and-namespaces/#rooms ). This does exactly what it sounds like, it emits the messages to the specific room where users have been added to when they connect to your application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM