I am using websockets/ws on single machine. Its working fine. I want to scale it horizontally on multi-core and on multiple instances. For mutli-core I tried with pm2 and it seems working great.
First Q: Is this the best approach or suitable approach? Here is my testing code with pm2
// ws-server.js
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3131 });
var pid = process.pid + ''
console.log('process pid: '+ pid)
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
if (message === 'get-pid') {
ws.send('pid-' + pid)
} else {
var matched = pid === message ? 'old friends' : 'strangers'
ws.send([pid, message, 'we are ' + matched].join(', '))
}
});
ws.send('first time')
});
and client websocket instances
// ws-cient.js
const WebSocket = require('ws');
const ws = new WebSocket('ws://localhost:3131/');
var pid
ws.on('open', function open() {
ws.send('get-pid');
setInterval(function() {
ws.send(pid)
}, 1000)
});
ws.on('message', function incoming(data) {
if (/^pid/.test(data)) {
pid = data.match(/\d+/)[0]
console.log('got pid: ' + pid)
} else {
console.log(data)
}
});
Just run the server and client with pm2
$ pm2 start ws-server.js -i 50
$ pm2 start ws-client.js -i 50
And if you see now the log pm2 logs ws-client
each client hits the same connection (at server) every second.
So for multi core ws works well with PM2.
Second Q: how to scale with multiple instances? I just saw SocketCluster for horizontal scaling, but can it be used along with websockets/ws as I have already developed code with ws. What could be other solution for horizontal scaling.