basic SSE examples for /events
This commit is contained in:
29
index.js
29
index.js
@@ -10,7 +10,8 @@ const express = require("express"); // could be good to replace with c
|
||||
// Get port or default to 8082
|
||||
const port = process.env.PORT || 8082;
|
||||
const protocol = 'https'
|
||||
const subclass = '192.168.4.'
|
||||
const subclass = '10.160.168.'
|
||||
//const subclass = '192.168.4.'
|
||||
|
||||
const publicKeyPath = path.resolve(process.env.HOME,'.ssh','id_rsa_offlineoctopus.pub')
|
||||
const publicKey = fs.readFileSync(publicKeyPath).toString().split(' ')[1]
|
||||
@@ -250,6 +251,7 @@ app.get('/scan', (req, res) => {
|
||||
})
|
||||
|
||||
function scanpeers(){
|
||||
sendEventsToAll({'action':'scanning started'})
|
||||
foundPeers = []
|
||||
for (let i=1;i<25;i++){ // async so blasting, gives very quick result for positives
|
||||
let url=protocol+'://'+subclass+i+':'+port+'/available'
|
||||
@@ -381,3 +383,28 @@ const webServer = https.createServer(credentials, app);
|
||||
webServer.listen(port, () => {
|
||||
console.log("listening on "+protocol+"://localhost:" + port);
|
||||
});
|
||||
|
||||
// SSE from https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app
|
||||
// adapted from jxr-permanence
|
||||
let clients = [];
|
||||
|
||||
function eventsHandler(request, response, next) {
|
||||
const headers = {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Connection': 'keep-alive',
|
||||
'Cache-Control': 'no-cache'
|
||||
};
|
||||
response.writeHead(200, headers);
|
||||
const clientId = Date.now();
|
||||
const newClient = { id: clientId, response };
|
||||
clients.push(newClient);
|
||||
request.on('close', () => { clients = clients.filter(client => client.id !== clientId); });
|
||||
}
|
||||
|
||||
function sendEventsToAll(data) {
|
||||
// function used to broadcast
|
||||
clients.forEach(client => client.response.write(`data: ${JSON.stringify(data)}\n\n`))
|
||||
}
|
||||
|
||||
app.get('/events', eventsHandler);
|
||||
// for example /events.html shows when /scan begings (but not ends)
|
||||
|
||||
Reference in New Issue
Block a user