Skip to content

Instantly share code, notes, and snippets.

@dsseng
Created February 2, 2018 15:25
Show Gist options
  • Save dsseng/ed4461a3eb3ae857e97da7488919a645 to your computer and use it in GitHub Desktop.
Save dsseng/ed4461a3eb3ae857e97da7488919a645 to your computer and use it in GitHub Desktop.
Node.js and UWS scalable chat server using Redis (ioredis)
var WebSocketServer = require('uws').Server;
var wss = new WebSocketServer({ port: 3000 });
var Redis = require('ioredis');
var redis = new Redis('localhost', 6379);
var pub = new Redis('localhost', 6379);
redis.subscribe('msg', function (err, count) {
// Now we are subscribed to the 'msg' channel.
// `count` represents the number of channels we are currently subscribed to.
console.log('subscribed')
});
redis.on('message', function (channel, message) {
console.log('Receive message %s from channel %s', message, channel);
if (channel === 'msg') {
wss.clients.forEach(c => {
c.send(message)
})
}
});
function onMessage(ws, msg) {
console.log('received: ' + msg);
pub.publish('msg', msg);
}
wss.on('connection', function (ws) {
ws.on('message', (msg) => onMessage(ws, msg));
});
@dsseng
Copy link
Author

dsseng commented Feb 2, 2018

P.S. try to run 3 same servers in Docker with Redis and Nginx as load balancer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment