-
Notifications
You must be signed in to change notification settings - Fork 578
/
ServerSentEvents.js
48 lines (41 loc) · 1.17 KB
/
ServerSentEvents.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
/* Server-sent events (EventSource) example */
/* curl -n localhost:9001 # check events by using curl */
const uWS = require('../dist/uws.js');
const port = 9001;
const headers = [
['Content-Type', 'text/event-stream'],
['Connection', 'keep-alive'],
['Cache-Control', 'no-cache']
]
function sendHeaders(res) {
for (const [header, value] of headers) {
res.writeHeader(header, value)
}
}
function serializeData(data) {
return `data: ${JSON.stringify(data)}\n\n`
}
const app = uWS./*SSL*/App({
key_file_name: 'misc/key.pem',
cert_file_name: 'misc/cert.pem',
passphrase: '1234'
}).get('/*', (res) => {
const clientId = Date.now()
console.log(`Client with id: ${clientId} connected, starting streaming`)
sendHeaders(res);
res.writeStatus('200 OK')
let intervalRef = setInterval(() => {
res.write(serializeData({ message: 'Hello world!' }))
}, 1000)
res.onAborted(() => {
clearInterval(intervalRef)
intervalRef = undefined
console.log(`Client with id: ${clientId} disconnected`)
})
}).listen(port, (token) => {
if (token) {
console.log('Listening to port ' + port);
} else {
console.log('Failed to listen to port ' + port);
}
});