dom-examples
dom-examples copied to clipboard
can you make a sse demo using nodejs?
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var clientId = 0;
var clients = {}; // <- Keep a map of attached clients
const server = http.createServer((req, res) => {
req.socket.setTimeout(Number.MAX_VALUE);
res.writeHead(200, {
'Content-Type': 'text/event-stream', // <- Important headers
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
(function (clientId) {
clients[clientId] = res; // <- Add this client to those we consider "attached"
req.on("close", function () {
delete clients[clientId]
}); // <- Remove this client when he disconnects
})(++clientId)
});
setInterval(function () {
var msg = Math.random();
console.log("Clients: " + Object.keys(clients) + " <- " + msg);
for (clientId in clients) {
clients[clientId].write("data: " + msg + "\n\n"); // <- Push a message to a single attached client
};
}, 2000);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});