forked from darrachequesne/socket.io-fiddle
-
Notifications
You must be signed in to change notification settings - Fork 28
/
server.js
35 lines (28 loc) · 852 Bytes
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { Server } from "socket.io";
const port = process.env.PORT || 3000;
const httpServer = createServer(async (req, res) => {
if (req.url !== "/") {
res.writeHead(404);
res.end("Not found");
return;
}
// reload the file every time
const content = await readFile("index.html");
res.writeHead(200, {
"Content-Type": "text/html",
"Content-Length": Buffer.byteLength(content),
});
res.end(content);
});
const io = new Server(httpServer, {});
io.on("connection", (socket) => {
console.log(`connect ${socket.id}`);
socket.on("disconnect", (reason) => {
console.log(`disconnect ${socket.id} due to ${reason}`);
});
});
httpServer.listen(port, () => {
console.log(`server listening at http://localhost:${port}`);
});