@InternalFX posted a good method; an alternative that you can use on Sails v0.10.x would be:
onConnect: function(session, socket) {
// If this is a logged in user, subscribe the socket to a
// custom "loggedInCount" room
if (session.user) {
var roomName = 'loggedIn'+session.user.id;
sails.sockets.join(socket, roomName);
// If this is the first subscriber, the user is just coming online,
// so notify any subscribers about the state change.
if (sails.sockets.subscribers(roomName).length == 1) {
User.message(session.user.id, {state: 'online'}, socket);
}
}
},
onDisconnect: function(session, socket) {
if (session.user) {
var roomName = 'loggedIn'+session.user.id;
sails.sockets.leave(socket, roomName);
// If this was the last subscriber, the user is going offline,
// so notify any subscribers about the state change.
if (sails.sockets.subscribers(roomName).length == 0) {
User.message(session.user.id, {state: 'offline'}, socket);
}
}
},
This uses Sails' built-in pubsub architecture to notify connected sockets whenever a particular user comes online or goes offline. It requires sockets to subscribe to the user instances they want to know about (using something like socket.get('/user')
on the client), which is a good practice to get into. This way you can be notified only about the users you care about (e.g. if you had a "friends list").