-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (50 loc) · 1.3 KB
/
index.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const express = require("express");
const cors = require("cors");
const http = require("http");
const WebSocket = require("ws");
const { randomUUID } = require("crypto");
const app = express();
const server = http.createServer(app);
const socket = new WebSocket.WebSocketServer({ server });
const PORT = process.env.PORT || 4000;
app.use(cors());
/** @type {{id: string, content: string, author: string}[]} */
const messages = [];
/**
* @param {string} content
* @param {string} author
*/
function onMessage(content, author) {
const message = {
id: randomUUID(),
content,
author,
};
messages.push(message);
socket.clients.forEach((client) => {
client.send(JSON.stringify({ type: "message", data: message }));
});
}
/**
* @param {WebSocket.WebSocket} ws
*/
function onConnection(ws) {
ws.on("message", (message) => {
try {
const { type, data } = JSON.parse(message);
switch (type) {
case "message":
onMessage(data.content, data.author);
break;
default:
break;
}
} catch (error) {
console.error(error.message);
}
});
}
socket.on("connection", onConnection);
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});