Created
February 2, 2018 15:25
-
-
Save dsseng/ed4461a3eb3ae857e97da7488919a645 to your computer and use it in GitHub Desktop.
Node.js and UWS scalable chat server using Redis (ioredis)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
P.S. try to run 3 same servers in Docker with Redis and Nginx as load balancer