Skip to content

Instantly share code, notes, and snippets.

@tomysmile
Forked from crtr0/client.js
Created January 22, 2018 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomysmile/0fd46454467f6c9f1f3a305f3caecff8 to your computer and use it in GitHub Desktop.
Save tomysmile/0fd46454467f6c9f1f3a305f3caecff8 to your computer and use it in GitHub Desktop.
A simple example of setting-up dynamic "rooms" for socket.io clients to join
// set-up a connection between the client and the server
var socket = io.connect();
// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";
socket.on('connect', function() {
// Connected, let's sign-up for to receive messages for this room
socket.emit('room', room);
});
socket.on('message', function(data) {
console.log('Incoming message:', data);
});
// attach Socket.io to our HTTP server
io = socketio.listen(server);
// handle incoming connections from clients
io.sockets.on('connection', function(socket) {
// once a client has connected, we expect to get a ping from them saying what room they want to join
socket.on('room', function(room) {
socket.join(room);
});
});
// now, it's easy to send a message to just the clients in a given room
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
// this message will NOT go to the client defined above
io.sockets.in('foobar').emit('message', 'anyone in this room yet?');
@zahidtariq
Copy link

What this MEANS?

io.sockets.in('foobar').emit('message', 'anyone in this room yet?');

@lockness-Ko
Copy link

io.sockets.in(roomname).emit(message, hi) broadcasts data to all the clients in the room (rooname)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment