-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.js
48 lines (38 loc) · 1.18 KB
/
events.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
var sys = require('sys');
var express = require('express');
var redis = require('redis');
function easyRedisEventStream(channel){
return function(req,res){
if(req.accepts('text/event-stream')){
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
});
var client = redis.createClient();
var eventChannel = channel
if(req.params.id){
eventChannel += req.params.id;
}
sys.log('subscribing to '+eventChannel);
client.subscribe(eventChannel);
client.on('message',function(channel,data){
res.write('data:'+data+'\n\n');
sys.log(channel+' - '+data);
});
req.on('close',function(){
sys.log('unsubscribing from '+eventChannel)
client.unsubscribe();
client.quit();
});
}else{
sys.log('EventStream called from non-EventStream location');
res.send(404);
}
}
}
var app = express.createServer();
app.get('/games',easyRedisEventStream('games'));
app.get('/games/:id/',easyRedisEventStream('game'));
app.get('/clashes/:id/',easyRedisEventStream('clash'));
app.listen(3001);
sys.log('listening on port 3001');