Skip to content

Instantly share code, notes, and snippets.

@devdemi
Created September 5, 2013 16:31
Show Gist options
  • Save devdemi/6452620 to your computer and use it in GitHub Desktop.
Save devdemi/6452620 to your computer and use it in GitHub Desktop.
var config = require('./config')
var redis1 = require("redis").createClient(config.redis.port, config.redis.host);
redis1.auth(config.redis.auth);
var subscribe = require("redis").createClient(config.redis.port, config.redis.host);
subscribe.auth(config.redis.auth);
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app);
app.listen(config.application.port);
app.setMaxListeners(0);
var clients = {};
var guests = {};
var channelPrefix = "new-messages-user-";
function handler (req, res) {
res.writeHead(200, {
"Access-Control-Allow-Origin": "*"
});
return res.end('pong');
}
io.of('/new-messages').on('connection', function (client) {
client.on("auth", function(sessId, userId){
console.log('AUTH: userId ' + userId)
var userIdFromRedis;
redis1.get(config.session_prefix + sessId, function (err , reply) {
if (reply){
reply = reply.toString();
var result = reply.match(/s:2:\"id\";i:(\d+);/);
if (result) {
userIdFromRedis = result[1]
console.log('AUTH: userIdFromRedis ' + userIdFromRedis)
} else {
result = reply.match(/s:7:\"guestId\";i:(\d+);/);
if (result) {
var guestIdFromRedis = result[1]
console.log('AUTH: guestIdFromRedis ' + guestIdFromRedis)
}
}
if (userIdFromRedis == userId) {
client.userId = userId;
subscribe.subscribe(channelPrefix + userId);
clients[userId] = client;
client.emit("auth", {"success":true});
console.log('AUTH: result - ok')
} else if (guestIdFromRedis) {
client.guestId = guestIdFromRedis;
subscribe.subscribe(channelPrefix + guestIdFromRedis);
clients[guestIdFromRedis] = client;
client.emit("auth", {"success":true});
console.log('AUTH: result - ok')
} else {
client.disconnect();
console.log('AUTH: result - fail')
}
} else {
client.disconnect();
}
});
})
subscribe.on("message", function(channel, message) {
var userId = Math.round(channel.substr(channelPrefix.length));
if (client.userId == userId || client.guestId == userId) {
console.log('Subscriber: ' + message)
client.send(message);
}
});
client.on("message", function(text){
client.send(text);
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment