Skip to content

Commit 823e1a9

Browse files
authored
Add ServerSentEvents.js example (#709) (#711)
1 parent 4ac42ec commit 823e1a9

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

‎examples/ServerSentEvents.js‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/* Server-sent events (EventSource) example */
2+
/* curl -n localhost:9001 # check events by using curl */
3+
4+
const uWS = require('../dist/uws.js');
5+
const port = 9001;
6+
7+
const headers = [
8+
['Content-Type', 'text/event-stream'],
9+
['Connection', 'keep-alive'],
10+
['Cache-Control', 'no-cache']
11+
]
12+
13+
function sendHeaders(res) {
14+
for (const [header, value] of headers) {
15+
res.writeHeader(header, value)
16+
}
17+
}
18+
19+
function serializeData(data) {
20+
return `data: ${JSON.stringify(data)}\n\n`
21+
}
22+
23+
const app = uWS./*SSL*/App({
24+
key_file_name: 'misc/key.pem',
25+
cert_file_name: 'misc/cert.pem',
26+
passphrase: '1234'
27+
}).get('/*', (res) => {
28+
const clientId = Date.now()
29+
console.log(`Client with id: ${clientId} connected, starting streaming`)
30+
sendHeaders(res);
31+
res.writeStatus('200 OK')
32+
33+
let intervalRef = setInterval(() => {
34+
res.write(serializeData({ message: 'Hello world!' }))
35+
}, 1000)
36+
37+
res.onAborted(() => {
38+
clearInterval(intervalRef)
39+
intervalRef = undefined
40+
console.log(`Client with id: ${clientId} disconnected`)
41+
})
42+
}).listen(port, (token) => {
43+
if (token) {
44+
console.log('Listening to port ' + port);
45+
} else {
46+
console.log('Failed to listen to port ' + port);
47+
}
48+
});

0 commit comments

Comments
 (0)