server.js
1.94 KB
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
var WebSocket = require('..'),
deflate = require('permessage-deflate'),
fs = require('fs'),
http = require('http'),
https = require('https');
var port = process.argv[2] || 7000,
secure = process.argv[3] === 'tls',
options = {extensions: [deflate], ping: 5};
var upgradeHandler = function(request, socket, head) {
var ws = new WebSocket(request, socket, head, ['irc', 'xmpp'], options);
console.log('[open]', ws.url, ws.version, ws.protocol, request.headers);
ws.pipe(ws);
ws.onclose = function(event) {
console.log('[close]', event.code, event.reason);
ws = null;
};
};
var requestHandler = function(request, response) {
if (!WebSocket.EventSource.isEventSource(request))
return staticHandler(request, response);
var es = new WebSocket.EventSource(request, response),
time = parseInt(es.lastEventId, 10) || 0;
console.log('[open]', es.url, es.lastEventId);
var loop = setInterval(function() {
time += 1;
es.send('Time: ' + time);
setTimeout(function() {
if (es) es.send('Update!!', {event: 'update', id: time});
}, 1000);
}, 2000);
fs.createReadStream(__dirname + '/haproxy.conf').pipe(es, {end: false});
es.onclose = function() {
clearInterval(loop);
console.log('[close]', es.url);
es = null;
};
};
var staticHandler = function(request, response) {
var path = request.url;
fs.readFile(__dirname + path, function(err, content) {
var status = err ? 404 : 200;
response.writeHead(status, {'Content-Type': 'text/html'});
response.write(content || 'Not found');
response.end();
});
};
var server = secure
? https.createServer({
key: fs.readFileSync(__dirname + '/../spec/server.key'),
cert: fs.readFileSync(__dirname + '/../spec/server.crt')
})
: http.createServer();
server.on('request', requestHandler);
server.on('upgrade', upgradeHandler);
server.listen(port);