1 |
3a515b92
|
cagy
|
const express = require('express')
|
2 |
|
|
const serveStatic = require('serve-static')
|
3 |
|
|
const SseStream = require('ssestream')
|
4 |
|
|
|
5 |
|
|
const app = express()
|
6 |
|
|
app.use(serveStatic(__dirname))
|
7 |
|
|
app.get('/sse', (req, res) => {
|
8 |
|
|
console.log('new connection')
|
9 |
|
|
|
10 |
|
|
const sseStream = new SseStream(req)
|
11 |
|
|
sseStream.pipe(res)
|
12 |
|
|
const pusher = setInterval(() => {
|
13 |
|
|
sseStream.write({
|
14 |
|
|
event: 'server-time',
|
15 |
|
|
data: new Date().toTimeString()
|
16 |
|
|
})
|
17 |
|
|
}, 1000)
|
18 |
|
|
|
19 |
|
|
res.on('close', () => {
|
20 |
|
|
console.log('lost connection')
|
21 |
|
|
clearInterval(pusher)
|
22 |
|
|
sseStream.unpipe(res)
|
23 |
|
|
})
|
24 |
|
|
})
|
25 |
|
|
|
26 |
|
|
app.listen(8080, (err) => {
|
27 |
|
|
if (err) throw err
|
28 |
|
|
console.log('server ready on http://localhost:8080')
|
29 |
|
|
})
|