-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (52 loc) · 1.45 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
63
const path = require("path");
const { Socket } = require("socket.io");
const Express = require("express");
const cors = require("cors");
const PORT = process.env.PORT || 5000;
const app = Express();
/** @type {Map<Socket, { id: string; address: string }>} */
let conns = new Map();
app.use(
cors({
origin: "/",
})
);
app.use("/", Express.static(path.join(__dirname, "/dist")));
const server = app.listen(PORT, () => console.log(`HTTP listening on ${PORT}`));
const io = require("socket.io")(server, {
cors: { origin: "*" },
path: "/io",
});
io.on("connection", (socket) => {
const address = socket.handshake.address;
console.log(`SOCKETIO: ${socket.id} connected`);
socket.on("join", (id) => {
conns.set(socket, { id, address });
io.emit("remote-users", getMapValues(conns, address));
});
socket.on("disconnect", () => {
conns.delete(socket);
console.log(`SOCKETIO: ${socket.id} disconnected`);
io.emit("remote-users", getMapValues(conns, address));
});
});
/**
*
* @param {Map<Socket, { id: string; address: string }>} map
* @param {string} clientAddress
* @returns
*/
function getMapValues(map, clientAddress) {
return Array.from(map.values())
.filter((oConn) => isOnSameNetwork(oConn.address, clientAddress))
.filter((oConn) => Boolean(oConn.id))
.map((oConn) => oConn.id);
}
/**
*
* @param {string} address1
* @param {string} address2
*/
function isOnSameNetwork(address1, address2) {
return true;
}