Created
December 21, 2018 07:49
-
-
Save compulim/fab7c9fece4e2fa126e830aa3e62861c to your computer and use it in GitHub Desktop.
Demo: HTTP/2 + Server-Sent Events
This file contains hidden or 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 http2 = require('http2'); | |
function main() { | |
const server = http2.createSecureServer({ | |
cert: CERTIFICATE, | |
key: PRIVATE_KEY | |
}); | |
server.on('error', err => console.error(err)); | |
server.on('stream', (stream, headers) => { | |
const path = headers[':path']; | |
if (path === '/') { | |
stream.respond({ | |
'content-type': 'text/html', | |
':status': 200 | |
}); | |
stream.end(HTML); | |
} else if (path === '/api/eventstream') { | |
stream.respond({ | |
'content-type': 'text/event-stream', | |
'cache-control': 'no-transform' | |
}); | |
const interval = setInterval(() => { | |
const now = Date.now(); | |
stream.write(`id: ${ now }\ndata: ${ new Date(now).toString() }\n\n`); | |
}, 1000); | |
stream.on('error', () => { | |
clearInterval(interval); | |
}); | |
} else { | |
stream.respond({ ':status': 404 }); | |
stream.end(); | |
} | |
}); | |
const { PORT = 5443 } = process.env; | |
server.listen(PORT, () => { | |
console.log(`Web server started on port ${ PORT }`); | |
}); | |
} | |
// To generate the certificate, run, and copy-and-paste the content below | |
// openssl req -x509 -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost:5443' -keyout localhost-privkey.pem -out localhost-cert.pem | |
const CERTIFICATE = `-----BEGIN CERTIFICATE----- | |
MII... | |
-----END CERTIFICATE-----`; | |
const PRIVATE_KEY = `-----BEGIN PRIVATE KEY----- | |
MII... | |
-----END PRIVATE KEY-----`; | |
const HTML = `<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Server-Sent Events demo</title> | |
<style type="text/css"> | |
pre { | |
background-color: #EEE; | |
border-radius: 5px; | |
padding: 5px; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Server-Sent Events demo</h1> | |
<script> | |
const eventSource = new EventSource('/api/eventstream'); | |
eventSource.addEventListener('message', ({ data }) => { | |
const pre = document.createElement('pre'); | |
pre.innerHTML = data; | |
document.body.appendChild(pre); | |
}); | |
</script> | |
</body> | |
</html>`; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment