Prerequisites
Additional helpful resources
- Scaling Websockets with Redis, HAProxy and Node JS - High-availability Group Chat Application
- Load Balancing NodeJS applications using NginX
- Socket.IO Docs - Using multiple nodes
- Socket.IO Docs - Adapters
- Socket.IO Docs - Redis adapter
Additional Tools
- nginx
- Redis
- Node.js v14+
- http-server
Here is a MSI installer I found for Redis.
Setup
- Clone repository
- cd into
server
andnpm install
Nginx conf
http {
upstream backend {
hash '$remote_addr $cookie_zzz $http_user_agent';
server 127.0.0.1:1212;
server 127.0.0.1:1213;
}
server {
listen 80;
root E:\\socket\\server;
location / {
proxy_pass http://backend;
}
}
}
events { }
https://stackoverflow.com/questions/59124543/nginx-not-loadbalancing-in-case-of-ip-hash
Running client
- cd into
client
- run
http-server . --cors --port=5500
Running server
- cd into
server
and open 2 terminals for the same directory - Set 2 different ports ( ex:
export PORT=1212
in one terminal andexport PORT=1213
in the other) - Start nginx with the given configuration
npm start
the server on both terminals
Now Server 1 will be started on PORT=1212
and Server 2 on PORT=1213
and the Client on PORT=5500
. Two servers will be load balanced using nginx on PORT=80
so the client will be directed to either Server 1 or 2 when it hits Port 80. Hash based load balancing is enabled (to achieve stickiness) since nginx open source doesn't allow cookie based load balancing. Go to http://127.0.0.1:5500/ with 2 browsers (Edge and Chrome for example) then the 2 instances will be connected to Server 1 and 2 respectively.
Redis will act as a PubSub mechanism and is enabled using Socket.IO Redis Adapter.
NOTE: Redis adapter will not store anything, it will only do PubSub.
If you want you can store data in Redis as well.