Skip to content

Instantly share code, notes, and snippets.

@kylewelsby
Last active July 25, 2022 06:25
Show Gist options
  • Save kylewelsby/2b49d2db31d45b939479 to your computer and use it in GitHub Desktop.
Save kylewelsby/2b49d2db31d45b939479 to your computer and use it in GitHub Desktop.
Socket.io joining a room

I client connects to a sever specifying a room they wish to join, that client is then binded to that one and only room.

The server broadcasts a event to the room, forwarding the message on to any other connected clients.

In the below example connected_client.js is listening to any messages, and will log the output.

[message]: {"room": "anything", "greeting": "Hello world"}
var socket = io.connect();
socket.emit('message', {event: 'something', data: {room: 'anything', greeting: 'Hello world'}});
var socket = io.connect();
socket.on('message', function(e){
console.log('[message]: ' + JSON.stringify(e));
});
var io = require('socket.io');
io.listen(app).on('connection', function(socket) {
function joinRoom(socket, room) {
if (socket.room) {
socket.leave(socket.room);
}
socket.join(room);
socket.room = room;
console.info(socket.id + ' joined room ' + room, socket.room);
}
socket.on('message', function(data, callback) {
if (data.event === 'connected' && data.data.room) {
socket.join(data.data.room);
console.log(socket.id + ' Joined Room ' + data.data.room);
socket.room = data.data.room // stash the room ID on the socket object to make it easy to recall.
}
socket.broadcast.to(socket.room).emit('message', data);
});
});
@superdev810
Copy link

How to get current room name here?

@andreyshedko
Copy link

Look like joinRoom function in server.js not being called from anywhere.

@kylewelsby
Copy link
Author

@audreyshedko you're right. This is 8-year-old code.
I suspect the function was intended to be called on line 16-18.

@andreyshedko
Copy link

@audreyshedko you're right. This is 8-year-old code.
I suspect the function was intended to be called on line 16-18.

Nice example, anyway.

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