Monthly Archives: June 2019

Get a list of connected clients in Socket.IO

As with broadcasting, the default is all clients from the default namespace (‘/’):

const io = require('socket.io')();  
io.clients((error, clients) => {
      if (error) throw error;
      console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});

Gets a list of client IDs connected to specific namespace (across all nodes if applicable):

const io = require('socket.io')();
io.of('/chat').clients((error, clients) => {
     if (error) throw error;
     console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});

An example to get all clients in namespace’s room:

const io = require('socket.io')();
io.of('/chat').in('general').clients((error, clients) => {
      if (error) throw error;
      console.log(clients); // => [Anw2LatarvGVVXEIAAAD] 
});

References
https://stackoverflow.com/questions/6563885/socket-io-how-do-i-get-a-list-of-connected-sockets-clients

Restricting yourself to a namespace on Socket.IO

Server

var io = require('socket.io')(80);
var chat = io
  .of('/chat')
  .on('connection', function (socket) {
    socket.emit('a message', {
        that: 'only'
      , '/chat': 'will get'
    });
    chat.emit('a message', {
        everyone: 'in'
      , '/chat': 'will get'
    });
  });

var news = io
  .of('/news')
  .on('connection', function (socket) {
    socket.emit('item', { news: 'item' });
  });

Client

<script>
  var chat = io.connect('http://localhost/chat')
    , news = io.connect('http://localhost/news');
  
  chat.on('connect', function () {
    chat.emit('hi!');
  });
  
  news.on('news', function () {
    news.emit('woot');
  });
</script>

References
https://socket.io/docs/#Restricting-yourself-to-a-namespace

Sending and receiving events on Socket.IO

Socket.IO allows you to emit and receive custom events. Besides connect, message and disconnect, you can emit custom events

Server

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

    socket.on("msg1", function (from, msg) {
        console.log('I received a message by ', from, ' saying ', msg);
    });

});

Client

$(document).ready(function () {
    var socket = io.connect('http://localhost:14000');
    socket.emit("msg1", "Mahmood", "Hello");
});

References
https://socket.io/docs/#Sending-and-receiving-events