35

I am trying to make a logged in user to join a certain socket.io room on connect. According to any examples I found on the net I seem to have emit some action from client to be able to join some room. Something like:

socket.on('connect', function() {
   socket.emit('join', 'room1');
});

Server.js:

io.sockets.on('connection', function(socket) {
    socket.on('join', function(room) {
        socket.join(room);
    });
});

And according to most tutorials it should work.

What I am thinkin to do is to:

socket.on('connect', function() {
   socket.join('room1');
});

But It does not seem to work as whatever msg I emit from server are not caught on client. Any idea, what am I doing wrong? Is it possible in general?

ArkadyB
  • 1,265
  • 1
  • 19
  • 37

3 Answers3

63

This should be what you need. Feel free to pass in whatever room name you want through the client. Only the server can handle assigning a socket to a room.

Server:

io.sockets.on('connection', function(socket) {
        socket.on('join', function(room) {
        socket.join(room);
    });
});

Client:

socket.emit('join', roomNum);
Falko
  • 17,076
  • 13
  • 60
  • 105
Bk Razor
  • 1,492
  • 1
  • 14
  • 24
44

There is no .join() method on the client side. Rooms are purely a server-side construct and the client knows nothing about them.

Your first block of code is the desired way to do things. You send the server a message of your design asking it to join the socket to a room and the .join() is executed on the server side.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
12

This is easily achieved. All you need to do is pass along a query parameter that the server understands.

The following example isn't fully tested, but the idea will work. In this example, the roomname is determined from window.location.href on the client.

Client

// Last segment of path is roomName
var roomName = window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
var socket = io({
    query: {
        roomName: roomName,
    },
});

Server

var io = require('socket.io')(server);
io.on('connection', function(socket) {
    var query = socket.handshake.query;
    var roomName = query.roomName;
    if(!roomName) {
        // Handle this as required
    }
    socket.join(roomName);
});
Guru Prasad
  • 4,053
  • 2
  • 25
  • 43
  • 5
    This is a good answer because someone can spoof the referrer header, it is harder to spoof the window href and you don't have to submit an additional emit() that comes with the risk of a drop off like the other answers. here's the docs on it [reference](https://socket.io/docs/client-api/#With-query-parameters) – soulshined Aug 29 '19 at 23:05