-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.ts
67 lines (59 loc) · 1.88 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
import "module-alias/register";
import ChatService from "@/app/server/helpers/ChatService";
import { createServer } from "http";
import next from "next";
import { parse } from "url";
import { WebSocket, WebSocketServer } from "ws";
const dev = process.env.NODE_ENV !== "production";
const hostname = dev ? "127.0.0.1" : undefined;
const port = Number(process.env.PORT || 3000);
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = createServer((req, res) => {
const parsedUrl = parse(req.url!, true);
handle(req, res, parsedUrl);
}).listen(port);
const chatService = new ChatService();
const wss = new WebSocketServer({ server });
const users = new Map();
function sendDataToEachClient(wss: WebSocketServer, data: any) {
const dataJson = JSON.stringify(data);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(dataJson);
}
});
}
wss.on("connection", (ws, req) => {
ws.on("close", () => {
users.delete(ws);
const usernames = users.values();
sendDataToEachClient(wss, {
users: Array.from(usernames),
type: "users",
});
});
ws.on("error", console.error);
ws.on("message", async (data) => {
const dataJson = data.toString();
const dataObj = JSON.parse(dataJson);
if (dataObj.type === "message") {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(dataJson);
}
});
await chatService.saveMessage(dataObj);
}
if (dataObj.type === "user-connected") {
users.set(ws, dataObj.username);
const usernames = users.values();
sendDataToEachClient(wss, {
users: Array.from(usernames),
type: "users",
});
}
});
});
});