Last active
September 20, 2022 19:17
-
-
Save Emyrk/ed0385d4798c8695d1f99196e0825f0c to your computer and use it in GitHub Desktop.
Express SSE Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const express = require('express'); | |
const fs = require('fs'); | |
const ws = require('ws'); | |
run().catch(err => console.log(err)); | |
async function run() { | |
const app = express(); | |
// Set up a headless websocket server that prints any | |
// events that come in. | |
const wsServer = new ws.Server({ noServer: true, path: "/websocket",}); | |
wsServer.on('connection', socket => { | |
socket.on('message', message => console.log(message)); | |
let i = 0; | |
setInterval(() => { | |
i++; | |
socket.send("WS"+i) | |
}, 1000) | |
}); | |
app.get('/events', async function(req, res) { | |
const clientID = Math.floor(Math.random() * 10000) | |
console.log('Got /events', clientID); | |
res.set({ | |
'Cache-Control': 'no-cache', | |
'Content-Type': 'text/event-stream', | |
'Connection': 'keep-alive' | |
}); | |
res.flushHeaders(); | |
// Tell the client to retry every 10 seconds if connectivity is lost | |
res.write('retry: 10000\n\n'); | |
let count = 0; | |
let go = true | |
req.on('close', () => { | |
go = false | |
}) | |
while (go) { | |
await new Promise(resolve => setTimeout(resolve, 1000)); | |
console.log('Emit', ++count); | |
// Emit an SSE that contains the current 'count' as a string | |
res.write(`data: ${count}\n\n`); | |
} | |
console.log("Request closed", clientID) | |
}); | |
// const index = fs.readFileSync('./index.html', 'utf8'); | |
app.get('/', (req, res) => res.send(`<html> | |
<body> | |
<div> | |
<h1>Server Sent Events</h1> | |
<div id="sse-content"></div> | |
</div> | |
<div> | |
<h1>Websocket Sent Events</h1> | |
<div id="ws-content"></div> | |
</div> | |
<script type="text/javascript"> | |
const source = new EventSource('/events'); | |
source.addEventListener('message', message => { | |
console.log('Got', message); | |
// Display the event data in the \`content\` div | |
document.querySelector('#sse-content').innerHTML = event.data; | |
}); | |
const ws = new WebSocket('ws://'+window.location.host+'/websocket'); | |
ws.onopen = (event) => { | |
console.log('WebSocket is connected.'); | |
}; | |
ws.onmessage = (event) => { | |
console.log('Got WS', event.data); | |
// Display the event data in the \`content\` div | |
document.querySelector('#ws-content').innerHTML = event.data; | |
} | |
</script> | |
</body> | |
</html>`)); | |
const server = app.listen(3000); | |
server.on('upgrade', (request, socket, head) => { | |
wsServer.handleUpgrade(request, socket, head, socket => { | |
wsServer.emit('connection', socket, request); | |
}); | |
}); | |
console.log('Listening on port 3000'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "sse-js-example", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"express": "^4.18.1", | |
"ws": "^8.8.1" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment