-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
50 lines (39 loc) · 1.19 KB
/
server.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
// https://stackoverflow.com/questions/53888030/why-do-server-sent-events-initiate-every-3-seconds
const PORT = 5000;
function randomInt() {
return Math.round(Math.random() * 100);
}
// const Koa = require("koa");
// const { PassThrough } = require("stream");
// const app = new Koa();
// app.use(async ctx => {
// ctx.set({
// "Access-Control-Allow-Origin": "*",
// Connection: "keep-alive",
// "Cache-Control": "no-cache"
// });
// const stream = new PassThrough();
// setInterval(() => {
// const data = { time: Math.round(Math.random() * 1000) };
// stream.write(`data: ${JSON.stringify(data)}\n\n`);
// }, 200);
// ctx.type = "text/event-stream";
// ctx.body = stream;
// });
// app.listen(PORT, () => console.log(`http://localhost:${PORT}`));
const http = require("http");
http
.createServer((req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream",
"Access-Control-Allow-Origin": "*",
});
setInterval(() => {
const data = {
value: randomInt()
};
res.write(`data: ${JSON.stringify(data)}`);
res.write("\n\n");
}, 500);
})
.listen(PORT, () => console.log(`http://localhost:${PORT}`));