forked from darrachequesne/socket.io-fiddle
-
Notifications
You must be signed in to change notification settings - Fork 28
/
server.js
43 lines (34 loc) · 978 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
36
37
38
39
40
41
42
43
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.onAny((ev) => {
console.log("onAny", ev);
});
socket.on("event", () => {
console.log("onevent");
});
socket.on("disconnect", (reason) => {
console.log(`disconnect ${socket.id} due to ${reason}`);
});
});
httpServer.listen(port, () => {
console.log(`server listening at http://localhost:${port}`);
});