Last active
April 19, 2020 00:31
-
-
Save jchip/e22ba49bcf33f634c368005f2606c00c 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
"use strict"; | |
const Http = require("http"); | |
class SimpleServer { | |
constructor({ port, name }) { | |
this._config = { port, name }; | |
this._routes = {}; | |
} | |
async start() { | |
this._server = Http.createServer((...args) => this._handler(...args)); | |
this._server.listen(this._config.port); | |
return this; | |
} | |
_handleErrors() { | |
this._server.on("error", err => { | |
console.log(`${this._name} error`, err); | |
}); | |
} | |
get(url, handler) { | |
this._routes[url] = handler; | |
return this; | |
} | |
_handler(req, res) { | |
const handler = this._routes[req.url]; | |
if (handler) { | |
return handler(req, res); | |
} | |
res.statusCode = 404; | |
res.end("not found"); | |
} | |
} | |
module.exports = { | |
SimpleServer | |
}; | |
function startEvents(req, res) { | |
res.writeHead(200, { | |
"content-type": "text/event-stream", | |
"cache-control": "no-cache", | |
"access-control-allow-origin": "*" | |
}); | |
let id = 1; | |
let count = 0; | |
res.socket.setKeepAlive(true); | |
const sendTimer = setInterval(() => { | |
res.write(`event: test\n`); | |
res.write(`id: ${id}\n`); | |
res.write(`data: count: ${count}`); | |
res.write(`\n\n`); | |
id++; | |
count++; | |
}, 500).unref(); | |
res.connection.on("close", () => { | |
console.log("event connection closed"); | |
clearInterval(sendTimer); | |
}); | |
} | |
async function app() { | |
(await new SimpleServer({ port: 8999 }).start()) | |
.get("/events", startEvents) | |
.get("/client", async (req, res) => { | |
res.writeHead(200, { | |
"content-type": "text/html" | |
}); | |
res.end(` | |
<html> | |
<head> | |
<script> | |
const es = new EventSource("http://localhost:8999/events"); | |
es.addEventListener("test", e => { | |
console.log("test", e); | |
}); | |
es.addEventListener("open", e => { | |
console.log("open", e); | |
}); | |
es.addEventListener("error", err => { | |
console.log("error", err); | |
}); | |
</script> | |
</head> | |
<body> | |
hello | |
</body> | |
</html> | |
`); | |
}); | |
} | |
app(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment