Last active
February 15, 2018 12:18
-
-
Save smashingpat/3d947179b41a901a26bb9fbf716adff6 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>SSE</title> | |
</head> | |
<body> | |
<script> | |
function startConnection() { | |
const stream = new EventSource('/event-stream') | |
stream.addEventListener('message', (event) => { | |
console.log('[SSE]:', JSON.parse(event.data)) | |
}) | |
stream.addEventListener('open', () => { | |
console.log('[SSE]: connected') | |
}) | |
} | |
startConnection() | |
</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 fs = require('fs') | |
const path = require('path') | |
const { | |
createServer | |
} = require('http') | |
let requestCounter = 0 | |
function handler(request, response) { | |
requestCounter++ | |
const requestCount = requestCounter | |
switch (request.url) { | |
case '/event-stream': | |
{ | |
console.log(`[SSE]: connection opened (${requestCount})`) | |
response.writeHead(200, { | |
'Content-Type': 'text/event-stream', | |
'Connection': 'keep-alive', | |
'Cache-Control': 'no-cache' | |
}) | |
response.write('\n\n') | |
const intervalId = setInterval(() => { | |
response.write(`data: <my data here>`) | |
response.write('\n\n') | |
}, 1000) | |
response.on('close', () => { | |
console.log(`[SSE]: connection closed (${requestCount})`) | |
clearInterval(intervalId) | |
}) | |
break | |
} | |
case '/': | |
{ | |
response.writeHead(200, { | |
'Content-Type': 'text/html' | |
}) | |
fs.createReadStream(path.resolve(__dirname, './index.html')) | |
.pipe(response) | |
break | |
} | |
default: | |
{ | |
response.writeHead(404, { | |
'Content-Type': 'text/plain' | |
}) | |
response.end('404 - Not Found') | |
break | |
} | |
} | |
} | |
createServer(handler) | |
.listen(4000, () => console.log('server listening')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment