Last active
October 23, 2018 12:06
-
-
Save jaguilar87/a2462f6d7861af50275ba931245a2f2f to your computer and use it in GitHub Desktop.
A test for Server Sent Events
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
<html> | |
<head> | |
<title>SSE example</title> | |
</head> | |
<body> | |
<h2>Messages:</h2> | |
<pre id="response"></pre> | |
<input id="message"> <button id="btnSubmit">Broadcast</button> | |
<script> | |
// Extremely simplified here, no error handling or anything | |
document.body.onload = function () { | |
var es = new EventSource('/stream'); | |
es.addEventListener('message', function (e) { | |
document.getElementById('response').innerHTML += JSON.parse(e.data).msg + '\n'; | |
}); | |
document.getElementById('btnSubmit').addEventListener('click', () => { | |
const msg = JSON.stringify({ msg: document.getElementById('message').value }); | |
console.log('Sending', msg); | |
fetch('/stream', { | |
headers: { 'Content-Type': 'application/json' }, | |
method: 'POST', | |
body: msg | |
}); | |
}) | |
} | |
</script> | |
</body> | |
</html> |
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
const express = require('express'); | |
const Sse = require('express-sse'); | |
const sse = new Sse(); | |
exports.getRouter = () => { | |
const app = new express.Router(); | |
app.get('/stream', sse.init); | |
app.post('/stream', exports.broadcast); | |
return app; | |
}; | |
exports.broadcast = (req, res) => { | |
sse.send(req.body); | |
res.send('OK'); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment