ufk
ufk

Reputation: 32104

detect namespace change in socket.io

I'm writing a nodeJS 0.12 application with express and socket.io.

I started with a small app. the user connects to socket.io and sees a button 'join_room' that actually joins the user to room\namespace 'a_b_c'.

so the javascript code on the client is simple:

var socket;

$(function () {
 socket = io();
  $('#join_room_button').click(function () {
    socket.emit("change_room","/a_b_c");
  });
});

so i have a button that the onclick emits the "change_room" with a room name.

in the server side i have the following code:

var io = require('socket.io')(server);
io.on('connection', function (socket) {
 console.log('user connected to socket.io');
  socket.on('change_room', function (data) {
    console.log("change room request to " + data);
    socket.join(data);
  })
});
var nsp = io.of('/a_b_c');
nsp.on('connection', function (socket) {
 console.log("someone connected to room a_b_c");
});

so as you can see here i catch a connection, and check if 'change_room' is emitted and if it is, i join the user to the room he asked for. below that code i check for a connected to that same room.

the problem is that i can't catch when the user connected to room '/a_b_c'. the signal or event never occurs even when the client clicks on change_room.

which means that the client sees the output: change room request to /a_b_c but the nsp variable with the connection is never called. any ideas?

Upvotes: 0

Views: 1077

Answers (1)

cdagli
cdagli

Reputation: 1578

I believe there is an misunderstanding with the usage of io.of, maybe you may check the selected answer's example in the below question;

io.of('namespace').emit('event', message) not working with namespace in socket.io

It listens a specific namespace but if you are trying to announce that someone joined in a specific room, you may send an event for that like below to the new room client joined;

var io = require('socket.io')(server);
io.on('connection', function (socket) {
 console.log('user connected to socket.io');
  socket.on('change_room', function (data) {
    console.log("change room request to " + data);
    socket.join(data);
    io.sockets.in(data).emit('user_joined', {msg: "...", user:"..."});
  })
});

Upvotes: 1

Related Questions