Last active
September 24, 2020 14:11
-
-
Save FelipeGrijo/6a22a65f43de61425ec80864a978ed01 to your computer and use it in GitHub Desktop.
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 SSE = new EventSource('http://localhost:3000'); | |
SSE.onmessage = (event) => { | |
const obj = JSON.parse(event.data); | |
console.log(obj); | |
}; |
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 http = require('http'); | |
const server = http.Server((req, res) => { | |
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; | |
const id = Math.random().toString(36).substr(2, 5); | |
console.log(`[START][${id}]`, req.method, req.url, ip); | |
const sseHeaders = { | |
Connection: 'keep-alive', | |
'Access-Control-Allow-Origin': '*', | |
'Cache-Control': 'no-cache', | |
'Content-Type': 'text/event-stream', | |
}; | |
res.writeHead(200, sseHeaders); | |
res.write(''); | |
const interval = setInterval(() => { | |
const data = { | |
id, | |
username: 'FelipeGrijo', | |
date: new Date(), | |
}; | |
res.write(`data:${JSON.stringify(data)}\n\n`); | |
}, 3000); | |
req.on('close', () => { | |
clearInterval(interval); | |
console.log(`[CLOSE][${id}]`, req.method, req.url, ip); | |
}); | |
}); | |
server.listen(3000, '0.0.0.0', () => { | |
console.log(`Server started on ${server.address().address}:${server.address().port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment