-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
72 lines (69 loc) · 2.03 KB
/
server.ts
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import http from "node:http";
import fs from "node:fs/promises";
import { Server } from "socket.io";
const PORT = 8080;
const app = http
.createServer(async (req, res) => {
const path = "." + (req.url == "/" ? "/index.html" : req.url);
console.log({ path });
try {
const file = await fs.readFile(path);
if (path.endsWith(".js")) {
res.setHeader("Content-Type", "text/javascript");
} else if (path.endsWith(".html")) {
res.setHeader("Content-Type", "text/html");
} else if (path.endsWith(".css")) {
res.setHeader("Content-Type", "text/css");
} else if (path.endsWith(".wasm")) {
res.setHeader("Content-Type", "application/wasm");
}
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
return res.end(file);
} catch (err) {
res.statusCode = 404;
res.end();
}
})
.listen(PORT);
console.log("Listening on http://localhost:8080");
type OutboundMessage =
| RTCSessionDescriptionInit
| RTCIceCandidateInit
| CandidateMessage
| "peerIsReady"
| "bye";
type InboundMessage = {
room: string;
userId: string;
message: OutboundMessage;
};
type CandidateMessage = {
type: "candidate";
label: number;
id: string;
candidate: string;
};
const io = new Server(app);
io.sockets.on("connection", function (socket) {
socket.on("message", function (message: InboundMessage) {
console.log("Client said: ", message);
for (const room of socket.rooms) {
if (room == message.room) {
socket.to(room).emit("message", message);
return;
}
}
console.error(`Couldn't find room ${message.room}`);
});
socket.on("joinRoom", (room: string) => {
console.log("Client ID " + socket.id + " joined room " + room);
io.sockets.in(room).emit("join", room);
socket.join(room);
socket.emit("joined", room, socket.id);
io.sockets.in(room).emit("ready");
});
socket.on("bye", function () {
console.log("received bye");
});
});