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?');
@welien
Copy link

welien 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
Copy link

S0ngyuLi commented Apr 15, 2017

Great example! Life saver

@kashyp18
Copy link

kashyp18 commented May 8, 2017

how to perform same operation in android

@giathinh910
Copy link

giathinh910 commented May 14, 2017

thanks

@RaymsDev
Copy link

RaymsDev commented Jul 6, 2017

thanks !

@asifvora
Copy link

asifvora 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
Copy link

yordis 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
Copy link

yordis 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
Copy link

lagost 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.

@nguyen-thom
Copy link

nguyen-thom commented May 30, 2018

Thank your

@keerthi2696
Copy link

keerthi2696 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
Copy link

ilaipi 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
Copy link

valay27 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.

@jaredleishman
Copy link

jaredleishman commented Feb 13, 2019

Thanks!

@ArnaldoLucienTema
Copy link

ArnaldoLucienTema commented Feb 22, 2019

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

@zahidtariq
Copy link

zahidtariq 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
Copy link

zahidtariq 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
Copy link

jeffmanful commented Mar 17, 2019

Thanks 👍

@tylim88
Copy link

tylim88 commented Apr 13, 2019

this example make thing simpler

@tgrlbyrk
Copy link

tgrlbyrk commented Apr 14, 2019

great example thanks!

@ldilshan
Copy link

ldilshan 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

@uplankita
Copy link

uplankita commented Mar 13, 2020

Thank you for a great example

@gudu1998
Copy link

gudu1998 commented May 5, 2020

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

Yeah socket.io docs is very bad .For basic knowledge of socket.io tutorial point is best

@FrankDev-327
Copy link

FrankDev-327 commented Aug 31, 2020

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

it's an example.

@suprth
Copy link

suprth commented Nov 17, 2020

Many thanks!

@0xPranavDoshi
Copy link

0xPranavDoshi commented Nov 23, 2020

Any idea on how to add other users to the room using their socketid.

@aandrade01
Copy link

aandrade01 commented Mar 16, 2022

In the client, how to receive only the messages of the room that was created?
Because in the way you gave as an example, the client receives any message and not just from the created room.

Thanks

@sharmavivek223
Copy link

sharmavivek223 commented Mar 29, 2022

How can i join room at backend with io instance and not socket instance?

@Roman-Vala
Copy link

Roman-Vala commented Apr 3, 2022

How can i join room at backend with io instance and not socket instance?

Hi, I think you can, if you put your room you want to join in in the query (room:"abc123") then your server will read it upon connection
as socket.handshake.query.room;
then join the appropriate room.

@C0rellana
Copy link

C0rellana commented Apr 12, 2022

Thanks!!

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