Created
November 26, 2018 22:02
-
-
Save efossas/a0b39b3e8835313fe0da91b27674bd18 to your computer and use it in GitHub Desktop.
Server Side Events Server
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
// this is the ExpressJS function you would put at /sse for setting up Server Side Events | |
async function(request, response) { | |
// for simplicity, we'll use a timestamp as an object key and for the first server event id (see below) | |
let timestamp = (+ new Date()); | |
// store the response so you can use it later in other parts of the code | |
request.app.get('connections')[timestamp] = response; | |
// server side events require mime type 'text/event-stream' | |
response.set({ | |
'Content-Type': 'text/event-stream', | |
'Cache-Control': 'no-cache', | |
'Connection': 'keep-alive' | |
}); | |
// keep the connection alive until we receive a close from the client | |
var connectionAlive = true; | |
request.connection.on('close',() => { | |
connectionAlive = false; | |
delete request.app.get('connections')[timestamp]; | |
}); | |
/* | |
server side events require an 'id' & two new lines at the end | |
*/ | |
let timestamp = (+ new Date()); | |
let event = `id: ${timestamp} | |
retry: 5000 | |
data: put some data here | |
`; | |
// send the event | |
response.write(event); | |
// if you don't keep the connection alive, the connection will automatically close | |
// and the server won't be able to send events later | |
while(connectionAlive) { | |
await sleep(5000); | |
} | |
}; | |
function sleep(ms) { | |
return new Promise(resolve => { | |
setTimeout(resolve, ms) | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment