Skip to content

Instantly share code, notes, and snippets.

@itsmebhavin
Forked from alexpchin/socket-cheatsheet.js
Last active April 3, 2017 15:08
Show Gist options
  • Select an option

  • Save itsmebhavin/cf117babc173258d3b323726beb5450b to your computer and use it in GitHub Desktop.

Select an option

Save itsmebhavin/cf117babc173258d3b323726beb5450b to your computer and use it in GitHub Desktop.
A quick cheatsheet for socket.io
// sending to sender-client only
socket.emit('message', "this is a test");
// sending to all clients, include sender
io.emit('message', "this is a test");
// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");
// sending to all clients in 'game' room(channel) except sender
socket.broadcast.to('game').emit('message', 'nice game');
// sending to all clients in 'game' room(channel), include sender
io.in('game').emit('message', 'cool game');
// sending to sender client, only if they are in 'game' room(channel)
socket.to('game').emit('message', 'enjoy the game');
// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');
// sending to individual socketid (server-side)
socket.broadcast.to(socketid).emit('message', 'for your eyes only');
// join to subscribe the socket to a given channel (server-side):
socket.join('some room');
// then simply use to or in (they are the same) when broadcasting or emitting (server-side)
io.to('some room').emit('some event'):
// leave to unsubscribe the socket to a given channel (server-side)
socket.leave('some room');
// the following two will emit to all the sockets connected to `/`
io.sockets.emit('hi', 'everyone');
io.emit('hi', 'everyone'); // short form
//-----------------------------------------------------
//Custom namespaces: To set up a custom namespace, you can call the of function on the server-side:
var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
console.log('someone connected');
});
nsp.emit('hi', 'everyone!');
//On the client side, you tell Socket.IO client to connect to that namespace:
var socket = io('/my-namespace');
//-----------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment