22

I'm on the socket.io wiki looking into using rooms but join and leave are not working, i'm wondering if they may have changed up a few things but not had the chance to update the wiki?

socket.join("room-"+data.meid);
socket.leave("room-"+meid);

cause im getting console errors:

Uncaught TypeError: Object #<SocketNamespace> has no method 'leave' 
Uncaught TypeError: Object #<SocketNamespace> has no method 'join' 
1

2 Answers 2

65

It looks like you had the socket.join on the client side. Its a server side function.

Put this on the server:

io.sockets.on('connection', function (socket) {

    socket.on('subscribe', function(data) { socket.join(data.room); })

    socket.on('unsubscribe', function(data) { socket.leave(data.room); })

});

setInterval(function(){
    io.sockets.in('global').emit('roomChanged', { chicken: 'tasty' });
}, 1000);

And this on the client:

var socket = io.connect();

socket.emit("subscribe", { room: "global" });

socket.on("roomChanged", function(data) {
    console.log("roomChanged", data);
});
3
  • 3
    Can you please explain what the setInterval() function does and its purpose? I am reading it as every 1 second send a message to all clients (in a room called global?) called roomChanged with the value chicken: tasty, but i don't understand what that would achieve. Commented Nov 21, 2018 at 10:06
  • Yes, that's what it does. Probably just to ping the client
    – GeekPeek
    Commented Feb 20, 2019 at 18:30
  • Can u please explain will this help in getting data live from Mysql db and show it in UI ? Will this avoid SetInterval which runs for 1 sec ? Commented Oct 22, 2020 at 19:22
30

You're probably not declaring 'socket' correctly either that of you haven't installed Socket-io correctly. Try the following...

var io = require("socket.io");

var socket = io.listen(80);

socket.join('room');

socket.leave('room');

There's a useful executable example here.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.