Sending session specific messages with socket.io a

2019-05-27 03:45发布

问题:

I'm trying to implement a private chat functionality, using sails.js framework, and i'm having some troubles when trying so send a message to a particular user.

Currently, I've achieved private communication by sending the messages to a particular socket.id, using the socket.io's .socket(socket.id).emit(event,message), but the problem with that approach is that every time the user opens a new tab, a new socket.id is generated, for that new connection.

And my question is: does sails.js facilitates a way of emitting events (using socket.io) to an specific user session instead of a bunch of socket ids? is it possible with these technologies?

So I can send the event only once, and making sure it is received in all the tabs where the chat app is currently open.

Thanks in advance.

回答1:

Sails augments all of its models with some useful pubsub methods. Whenever you find a model via a socket request (e.g. socket.get('/user/123') ) the requesting socket is automatically subscribed to all messages about that model. You can then call User.message(123, data) to send a message to all of the connected sockets for that user.

Docs for the pubsub methods are here.