socket io subscribe code example

Example 1: socket io connect to namespace

var io  = require('socket.io')(http, { path: '/myapp/socket.io'});

io
.of('/my-namespace')
.on('connection', function(socket){
    console.log('a user connected with id %s', socket.id);

    socket.on('my-message', function (data) {
        io.of('my-namespace').emit('my-message', data);
        // or socket.emit(...)
        console.log('broadcasting my-message', data);
    });
});

Example 2: rooms in socket io

io.on('connection', socket => {
  socket.join('some room');
});
//And then simply use to or in (they are the same) when broadcasting or emitting:

io.to('some room').emit('some event');
//You can emit to several rooms at the same time:

io.to('room1').to('room2').to('room3').emit('some event');
//In that case, an union is performed: every socket that is at least in one of the rooms will get the event once (even if the socket is in two or more rooms).
//You can also broadcast to a room from a given socket:

io.on('connection', function(socket){
  socket.to('some room').emit('some event');
});