This repository has been archived by the owner on May 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
70 lines (62 loc) · 1.61 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var redis = require('redis').createClient()
, memcache = require('memcache')
, server = require('http').createServer()
, io = require('socket.io').listen(server)
, cookie = require('cookie')
, sockets = {};
// connect to memcache on default host/port
mcClient = new memcache.Client()
mcClient.connect();
// run HTTP server on this port
server.listen(3000);
// only allow authenticated connections
io.set('authorization', function(handshake, callback)
{
var cookies = cookie.parse(handshake.headers.cookie);
mcClient.get('sessions/' + cookies.PHPSESSID, function(error, result)
{
if (error)
{
callback(error, false);
}
else if (result)
{
handshake.session = JSON.parse(result);
callback(null, true);
}
else
{
callback('Could not find session ID ' + cookies.PHPSESSID + ' in memcached', false);
}
});
});
io.sockets.on('connection', function(socket)
{
var session = socket.handshake.session;
console.log('Received connection from user:', session.user);
// store user's socket
sockets[session.user.username] = socket;
});
getNews();
function getNews()
{
redis.blpop('news', 0, function(err, data)
{
news = JSON.parse(data[1]);
if (typeof news.to !== 'undefined')
{
if (typeof sockets[news.to] !== 'undefined')
{
// send just the given user the news
sockets[news.to].emit('news', news.content);
}
}
else
{
// send everyone the news
io.sockets.emit('news', news.content);
}
// check for more data in next run of the event loop
process.nextTick(getNews);
});
}