-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
44 lines (36 loc) · 975 Bytes
/
server.js
File metadata and controls
44 lines (36 loc) · 975 Bytes
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
const http = require('http');
const fs = require('fs');
http.createServer(function(req, res) {
if (req.headers.accept == 'text/event-stream') {
if (req.url == '/events') {
sendSSE(req, res);
} else {
res.writeHead(404);
res.end();
}
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync(__dirname + '/sse-node.html'));
res.end();
}
}).listen(3000);
console.log('listening on 3000');
function sendSSE(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive'
});
var id = 0;
setInterval(function() {
id++;
constructSSE(res, id, (new Date()).toLocaleTimeString());
}, 1000);
constructSSE(res, id, (new Date()).toLocaleTimeString());
}
function constructSSE(res, id, data) {
res.write('id: ' + id + '\n');
if(id % 2 === 0){
res.write('event: ' + 'specialEvent' + '\n');
}
res.write("data: " + data + '\n\n');
}