Skip to content

Instantly share code, notes, and snippets.

@bricecarpentier
Last active March 29, 2021 21:12
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bricecarpentier/5599799 to your computer and use it in GitHub Desktop.
Save bricecarpentier/5599799 to your computer and use it in GitHub Desktop.
This is a simple websocket server coded using nodejs and http://einaros.github.io/ws/ connecting to a redis pubsub channel and sending messages to selected clients
var ws = require('ws'),
nconf = require('nconf'),
redis = require('redis');
nconf.argv()
.env();
var server = new ws.Server({port: nconf.get('PORT')});
var sockets = {};
server.on('connection', function(socket) {
socket.on('message', function(message) {
var a = message.split('|');
var playerId = a[0];
console.log('received message from ' + playerId);
sockets[playerId] = socket;
});
});
var db = redis.createClient(nconf.get("REDIS_PORT"), nconf.get("REDIS_HOST"));
if (nconf.get('REDIS_PASSWORD')) {
db.auth(nconf.get("REDIS_PASSWORD"));
}
db.on('message', function(channel, message) {
if (channel == 'chanel')
{
var a = message.split('>');
var socket = sockets[a[0]];
var m = a[1];
// les messages sont supposés contenir les ID utilisateurs
//var socket = sockets[message];
if (socket != undefined)
{
socket.send(m);
}
}
});
db.subscribe('channel');
console.log('listening at ws://localhost:' + nconf.get('PORT'));
@mohamedmostafaa
Copy link

Can you Please Help me to integrate your code with my API Server?

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