Skip to content

Instantly share code, notes, and snippets.

@TahaBoulehmi
Last active June 20, 2019 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TahaBoulehmi/6aa6cfca57de0a2a31c527187bb730bb to your computer and use it in GitHub Desktop.
Save TahaBoulehmi/6aa6cfca57de0a2a31c527187bb730bb to your computer and use it in GitHub Desktop.
Using Raw Socket IO In Sails.js
module.exports = {
/**
*
* Using raw socket.io functionality from a Sails.js controller
*
*/
index: function (req,res) {
var socket = req.socket;
var io = sails.io;
// emit to all sockets (aka publish)
// including yourself
io.sockets.emit('messageName', {thisIs: 'theMessage'});
// broadcast to a room (aka publish)
// excluding yourself, if you're in it
socket.broadcast.to('roomName').emit('messageName', {thisIs: 'theMessage'});
// emit to a room (aka publish)
// including yourself
io.sockets.in('roomName').emit('messageName', {thisIs: 'theMessage'});
// Join a room (aka subscribe)
// If you're in the room already, no problem, do nothing
// If the room doesn't exist yet, it gets created
socket.join('roomName');
// Leave a room (aka unsubscribe)
// If you're not in the room, no problem, do nothing
// If the room doesn't exist yet, no problem, do nothing
socket.leave('roomName');
// Get all connected sockets in the app
sails.io.sockets.clients();
// Get all conneted sockets in the room, "roomName"
sails.io.sockets.clients('roomName');
}
};
//Client
//If you need to use .emit() in sails.socket, you should use _raw.emit()
io.socket._raw.emit('eventName', jsonData);
//io.socket._raw will get the raw, underlying socket.io instance on the client, which will have the emit method.
//But this is not the recommended practice. With Sails Socket it is better to use .get(), .post(), .put(), or .delete().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment