Socket.IO subscribe to multiple channels

Solution 1:

This is all pretty straightforward with the socket.io rooms feature. Take a look at the documentation on LearnBoost wiki.

https://github.com/LearnBoost/socket.io/wiki/Rooms

It allows for being connected to multiple rooms over a single socket. I put together a quick test with the following code.

Server

io.sockets.on('connection', function(client){
    client.on('subscribe', function(room) { 
        console.log('joining room', room);
        client.join(room); 
    })
    
    client.on('unsubscribe', function(room) {  
        console.log('leaving room', room);
        client.leave(room); 
    })

    client.on('send', function(data) {
        console.log('sending message');
        io.sockets.in(data.room).emit('message', data);
    });
});

Client

 var socket = io.connect();
 socket.on('message', function (data) {
  console.log(data);
 });
 
 socket.emit('subscribe', 'roomOne');
 socket.emit('subscribe', 'roomTwo');
 
 $('#send').click(function() {
  var room = $('#room').val(),
   message = $('#message').val();
   
  socket.emit('send', { room: room, message: message });
 });

Sending a message from an Express route is pretty simple as well.

app.post('/send/:room/', function(req, res) {
    var room = req.params.room
        message = req.body;

    io.sockets.in(room).emit('message', { room: room, message: message });

    res.end('message sent');
});