Apache reverse proxy configuration for socket.io

sudo a2enmod proxy_http
sudo a2enmod proxy_fcgi
sudo a2enmod proxy_wstunnel
# VirtualHost ms.example.net
<VirtualHost *:80>
  ServerName ms.example.net
  ProxyRequests Off
  ProxyPreserveHost On
  RemoteIPHeader X-Forwarded-For
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>
  RewriteEngine On
  RewriteCond %{REQUEST_URI} ^/socket.io          [NC]
  RewriteCond %{QUERY_STRING} transport=websocket [NC]
  RewriteRule /(.*) ws://localhost:14102/$1        [P,L]

  ProxyPass /socket.io http://localhost:14102/socket.io
  ProxyPassReverse /socket.io http://localhost:14102/socket.io
</VirtualHost>

<VirtualHost *:443>
  ServerName ms.example.net
  ProxyRequests Off
  ProxyPreserveHost On
  RemoteIPHeader X-Forwarded-For
  RewriteEngine on
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>
  SSLEngine On
  SSLCertificateFile /etc/letsencrypt/live/example.net/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/example.net/privkey.pem
  
  RewriteEngine On
  RewriteCond %{REQUEST_URI} ^/socket.io          [NC]
  RewriteCond %{QUERY_STRING} transport=websocket [NC]
  RewriteRule /(.*) ws://localhost:14102/$1        [P,L]
  ProxyPass /socket.io http://localhost:14102/socket.io
  ProxyPassReverse /socket.io http://localhost:14102/socket.io
  
</VirtualHost>

Use a secure URL for your initial connection, i.e. instead of “http://” use “https://”. If the WebSocket transport is chosen, then Socket.IO should automatically use “wss://” (SSL) for the WebSocket connection too.

var socket = io.connect('https://localhost', {secure: true});

References
http://xpo6.com/socket-io-via-apache-reverse-proxy/
https://stackoverflow.com/questions/36472920/apache-proxy-configuration-for-socket-io-project-not-in-root
https://gist.github.com/iacchus/954e0787d6893c5ab8e1
https://stackoverflow.com/questions/6599470/node-js-socket-io-with-ssl

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

Connect to Socket.IO Server

Server

var express = require('express');
var app = express();
var logger = require('morgan');
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.use(express.static('public'));

app.use(logger('dev'));
server.listen(14000);

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/public/index.html');
});

io.on('connection', function (socket) {
    console.log("Connected : " + socket.client.id);
});

Client

$(document).ready(function () {
    var socket = io.connect('http://localhost:14000');
});

References
https://socket.io/docs/#Using-with-Express