Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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?');
@kmlx

This comment has been minimized.

Copy link

commented Feb 1, 2013

Great example! Thanks!

@hyperprodigy

This comment has been minimized.

Copy link

commented Feb 8, 2013

Please write example for "io.sockets.clients(room)", how can i see who in room online ??

@nestornav

This comment has been minimized.

Copy link

commented Feb 15, 2013

Your example is so helpfull but I have a question. How can I take off a client?

@nestornav

This comment has been minimized.

Copy link

commented Feb 15, 2013

I found an ansewer of my question in this post:https://github.com/LearnBoost/socket.io/wiki/Rooms

and also can help to hyperprodify with their question.

Regards

@yairEO

This comment has been minimized.

Copy link

commented May 11, 2013

are the clients inside the room stored as Array? how can I access the list of clients in a certain room and see who they are?

@lambtron

This comment has been minimized.

Copy link

commented May 25, 2013

Carter, this is awesome. Is it possible to do this with Socket.io namespaces?

@tom2strobl

This comment has been minimized.

Copy link

commented Jun 21, 2013

Just wanted to say thank you for simplifying it! Totally get it know.

@bbog

This comment has been minimized.

Copy link

commented Jul 4, 2013

A huge "Thank you!" from myself as well! I've been struggling to achieve this for quite some time with no result... All the other tutorials or articles I've read don't cover the basic not even nearly as well! Now I can finally advance with my project!

@RienNeVaPlus

This comment has been minimized.

Copy link

commented Jul 24, 2013

For those who wonder how to leave the previous room, if a active user joins (switches to) another room, try this:

server.js

socket.on('room', function(room){
    if(socket.room)
        socket.leave(socket.room);

    socket.room = room;
    socket.join(room);
});
@devildeveloper

This comment has been minimized.

Copy link

commented Aug 11, 2013

a customer can be in more than one room ?

@ghost

This comment has been minimized.

Copy link

commented Aug 14, 2013

Yes, users can be in any number of rooms at once

@popkinj

This comment has been minimized.

Copy link

commented Sep 9, 2013

Great example... Thanks :)

@gooooloo

This comment has been minimized.

Copy link

commented Mar 15, 2014

Great. It helps a lot. Thanks.

@ankitsabharwal

This comment has been minimized.

Copy link

commented Apr 11, 2014

This is helpful!

@insaneitskills

This comment has been minimized.

Copy link

commented Jun 17, 2014

Check this interactive course that gives you all the keys to a good start for a complete masteration of node.js by taking all the power of it.
This course is regularly updated.
https://www.udemy.com/nodejs-tutorial-from-scratch-by-examples

@popkinj

This comment has been minimized.

Copy link

commented Sep 24, 2014

Thanks for this. ☺

@reijmer

This comment has been minimized.

Copy link

commented Sep 28, 2015

Thanks, this helped me!

@jonathanwoahn

This comment has been minimized.

Copy link

commented Nov 7, 2015

Thank you! Super helpful!

@stewartcelani

This comment has been minimized.

Copy link

commented Dec 31, 2015

Thanks very much for this. =)

@Emilios1995

This comment has been minimized.

Copy link

commented Feb 12, 2016

This is definitely helpful!
Socket.io's docs don't provide much info about this.

@aa2kb

This comment has been minimized.

Copy link

commented Feb 23, 2016

Damm ! That Simple.

@rChavz

This comment has been minimized.

Copy link

commented Mar 9, 2016

and where is the dynamic example?

@liuzy0404

This comment has been minimized.

Copy link

commented Mar 16, 2016

Very useful, thanks~

@davidvuong

This comment has been minimized.

Copy link

commented Apr 19, 2016

Created 4 years ago

Still useful. Thanks!

@gayathrig321

This comment has been minimized.

Copy link

commented May 9, 2016

Very useful, clear....thank you so much..

@dvp236

This comment has been minimized.

Copy link

commented May 12, 2016

Thanks !

@mayankkamboj47

This comment has been minimized.

Copy link

commented Jun 21, 2016

You make it look so easy

@marceloleiva

This comment has been minimized.

Copy link

commented Jul 10, 2016

Thanks :)

@oilwer

This comment has been minimized.

Copy link

commented Jul 26, 2016

Cheers!

@AndrewGardhouse

This comment has been minimized.

Copy link

commented Sep 2, 2016

Thanks 👍

@itsreallyike

This comment has been minimized.

Copy link

commented Sep 13, 2016

THANK YOU!

@horcrux95

This comment has been minimized.

Copy link

commented Sep 21, 2016

thank you :)

@surfjedi

This comment has been minimized.

Copy link

commented Oct 21, 2016

Does this work in 1.5?

@BenjaminMonge

This comment has been minimized.

Copy link

commented Nov 5, 2016

Thank you for the clear example

@justinliow

This comment has been minimized.

Copy link

commented Nov 14, 2016

thank you so much

@daryn-k

This comment has been minimized.

Copy link

commented Dec 25, 2016

server.js line 13 room = "abc123"; - is it hardcode? if so, it's seems to me stupid.

@benpoulson

This comment has been minimized.

Copy link

commented Dec 30, 2016

@daryn-k It's only there as an example. You can swap this out for any dynamic room ID method.

@NguyenTungs

This comment has been minimized.

Copy link

commented Feb 24, 2017

Hi everyone!
I can ask a question?
How to Client can join multiple room and receive 2 notifications the same time for different two rooms.

@deshario

This comment has been minimized.

Copy link

commented Mar 10, 2017

Can we joined room permanently .... actually i am developing node + socket application as gameserver and client is unity ... and i join p1 to room when he invite to p2 ... and p2 was joined when he accept p1 invitation ! after that i had emmited to that joined room >> it works perfectly !
But after i had emmited function to this room .. in unity i had change scene of both connected clients and in that scene there is a one button for both p1 and p2 to click start game ... when i click this button ... it will emit to server to start game for both clients ! but problem is when i emit to that room .... no clients are connected .... so i wanna join permanently !
Thankx for any advance ...

@Arcanius

This comment has been minimized.

Copy link

commented Apr 6, 2017

Is there any way to assign some data to a room? So that it will be shared with other sockets by reference? For example if two players were in a room and played tic tac toe and I wanted to save game board state somewhere.

@S0ngyuLi

This comment has been minimized.

Copy link

commented Apr 15, 2017

Great example! Life saver

@kashyp18

This comment has been minimized.

Copy link

commented May 8, 2017

how to perform same operation in android

@giathinh910

This comment has been minimized.

Copy link

commented May 14, 2017

thanks

@RaymsDev

This comment has been minimized.

Copy link

commented Jul 6, 2017

thanks !

@asifvora

This comment has been minimized.

Copy link

commented Oct 10, 2017

how can we create a dynamically room for particular 2 player.
ex : player - 1 and player - 2 connect in Room-1 when come player - 3 than create a room 2 and join they and check the player in each room.
if Room-1 connect player - 1 so player -2 connect with room-1.
when connect player-3 create new room-2 for that.

@yordis

This comment has been minimized.

Copy link

commented Nov 30, 2017

I think this will help a lot of people, I am just using Firebase but the concept is the same, you just find somehow the identifier of your connected user and join it automatically

// server side
const debugSocket = debug('debug')('myAppName:socket')

const Channel = IOServer(...)

const CustomerChannel =
  Channel
  .of('/customer') // I am using another channel but it doesn't not matter, just showing an example
  .on('connection', async (socket)=> {
    debugSocket('CustomerChannel: Connected')
    let currentUser = null

    // I am using firebaseToken key from the query but does not matter
    // you could switch to whichever key you want as long as it is useful
    // for find your user
    if(socket.handshake.query && socket.handshake.query.firebaseToken) {
        currentUser = await firebase.auth().verifyIdToken(socket.handshake.query.firebaseToken)
        // being fancy, make sure that currentUser is not undefined or null
       // or whatever your await function could have, that is a business rule


        // Either Firebase callback or you just do some database lookup
        // using some useful information from the token
        debugSocket(`CustomerChannel:Room:Joined: ${user.email}`)
        // Whatever the callback returns me I will use some idetifier
        // and I will use it as the ID of my room
        socket.join(user.uid)
    }

    socket.on('disconnect', (reason) => {
      if(currentUser) {
        debugSocket(`CustomerChannel:Room:Leaved: ${user.email}`)
          // Same concept here I am just disconnecting the user from his own
          // This is because you can still connected to CustomerChannel
          // but not to your room, this depends of your use case
        socket.leave(currentUser.uid)
      }
    })
  })

In the client you need to make sure that you send the query parameter when you connect to the channel

// client side
io(`/customer`, {
      query: {
        token: 'whatever' // just make sure you have the information before you connect to the channel
      }
    })

Now the second part is to send messages to specific room.

// server code

// somewhere in my backend code
// I have to have the identifier of the user to be able to send him and only him messages
// so somehow I HAVE TO HAVE `user` loaded and then I will use it `uid` which was the way
// I joined the user to his room.
CustomerChannel.to(user.uid).emit('hello', { message: 'World'})

I hope you find it useful.

Cheers.

@yordis

This comment has been minimized.

Copy link

commented Nov 30, 2017

If what you want is to connect multiple people to the same room, then just send roomId: "" in the query which somehow you had to find it before, right!? Somebody have to create specific room somehow, either you create some database that have it them or you just type the roomID whatever you do.

And then instead of user the user.uid just use the roomId and done.

After that in your backend code, somehow you HAVE TO HAVE the roomId you want to send the data to.

@lagost

This comment has been minimized.

Copy link

commented Feb 8, 2018

Would anyone know if rooms can only emit text?
I am trying to emit an image on canvas to one specific room and it won't work.
It will however work if I emit a text message.

@thomnv

This comment has been minimized.

Copy link

commented May 30, 2018

Thank your

@keerthi2696

This comment has been minimized.

Copy link

commented Jul 6, 2018

Hi,

I am having a room how can I add new user to the same room in socket.io. I can't find a way please help me.

@ilaipi

This comment has been minimized.

Copy link

commented Oct 22, 2018

Hi,

I am having a room how can I add new user to the same room in socket.io. I can't find a way please help me.

I think you can just give the same name to any new user.

@valay27

This comment has been minimized.

Copy link

commented Nov 14, 2018

In Socket When new connection join the room at that time its remove last connected socket from the room can you please help me on this if someone know ? Also didn't get any error when i debugging.

@iamjleishman

This comment has been minimized.

Copy link

commented Feb 13, 2019

Thanks!

@ArnaldoLucienTema

This comment has been minimized.

Copy link

commented Feb 22, 2019

A great example, simple and useful. Thank you sir.

@zahidtariq

This comment has been minimized.

Copy link

commented Mar 16, 2019

Can anyone tell me that how we can randomly adjust the sockets to different rooms at the same time not one room?

@zahidtariq

This comment has been minimized.

Copy link

commented Mar 16, 2019

A great example, simple and useful. Thank you sir.

Can YOu tell me that how we can randomly adjust the sockets to different rooms at the same time not one room?

@jeffmanful

This comment has been minimized.

Copy link

commented Mar 17, 2019

Thanks 👍

@tylim88

This comment has been minimized.

Copy link

commented Apr 13, 2019

this example make thing simpler

@tgrlbyrk

This comment has been minimized.

Copy link

commented Apr 14, 2019

great example thanks!

@ldilshan

This comment has been minimized.

Copy link

commented May 9, 2019

Anyone can tell me how to assign users from the db or active users in to specific Room. Where can we handle that?

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.