Skip to content

Instantly share code, notes, and snippets.

@viniazvd
Last active August 23, 2023 20:18
Show Gist options
  • Save viniazvd/0e70f0e946c60090e9c12d175fd3e52d to your computer and use it in GitHub Desktop.
Save viniazvd/0e70f0e946c60090e9c12d175fd3e52d to your computer and use it in GitHub Desktop.
sse.js
const cors = require('cors')
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
let clients = []
const addSubscribe = (req, res) => {
res.writeHead(200, { Connection: 'keep-alive', 'Content-Type': 'text/event-stream' })
const id = Date.now()
clients.push({ id, res })
console.log(`Client connected: ${id}`)
req.on('close', () => {
console.log(id)
clients = clients.filter((client) => client.id !== id)
})
}
const addMessage = (req, res) => {
const msg = req.body
res.json(msg)
clients.forEach((client) => client.res.write(`data: ${JSON.stringify(msg)}\n\n`))
}
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.post('/message', addMessage)
app.get('/subscribe', addSubscribe)
app.get('/status', (_, res) => res.json(clients.length))
app.listen(3000, () => console.log(`App listening on port ${3000}`))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment