-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
45 lines (35 loc) · 1.25 KB
/
index.ts
File metadata and controls
45 lines (35 loc) · 1.25 KB
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
import {WebSocketServer, WebSocket as WS} from "ws";
import {fileURLToPath} from "url";
import {join, dirname} from "path";
import {readdirSync} from "fs";
const port: number = 8080;
const ws = new WebSocketServer({port});
const __filename: string = fileURLToPath(import.meta.url);
const __dirname: string = dirname(__filename);
type request_type = (server: WebSocketServer, client: WS, json: Record<string, any>) => void;
const __types: Record<string, request_type> = {};
const dir = join(__dirname, "src", "requests_type");
for (const file of readdirSync(dir)) {
const func: request_type = (await import(`./src/requests_type/${file}`)).default;
__types[file.replace(".ts", "")] = func
}
type authenticated_ws = WS & {
__username: string
}
ws.on("connection", (client: WS) => {
console.log("new client connected");
client.on("message", (raw_payload: string) => {
const payload = raw_payload.toString();
if (!payload) return;
let json: Record<string, any>;
try {
json = JSON.parse(payload);
} catch {
return;
}
const func = __types[json.__request];
if (!func) return;
func(ws, client, json);
});
})
console.log("WS server rodando na porta " + port)