-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
44 lines (34 loc) · 856 Bytes
/
server.js
File metadata and controls
44 lines (34 loc) · 856 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
const fs = require('fs');
const http2 = require('http2');
const HTTPSoptions = {
key: fs.readFileSync('./cert/selfsigned.key'),
cert: fs.readFileSync('./cert/selfsigned.crt'),
};
const template = `
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
const source = new EventSource('/sse/');
source.onmessage = function(e) {
document.body.innerHTML += e.data + '<br>';
};
</script>
</body>
</html>
`;
const server = http2.createSecureServer(HTTPSoptions);
server.on('request', (req, res) => {
req.socket.setKeepAlive(true);
if(req.url === '/sse/') {
res.writeHead(200, {
'Content-Type': 'text/event-stream', // <- Important headers
'Cache-Control': 'no-cache'
});
res.write('\n');
setInterval(() => res.write(`data: ${Math.random()}\n\n`), 200);
} else {
res.end(template);
}
});
server.listen(3000);