Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (58 loc) · 1.78 KB
/
Copy pathindex.js
File metadata and controls
74 lines (58 loc) · 1.78 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
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
73
const WebSocket = require("ws");
const querystring = require("querystring");
const server = require("http").createServer();
const port = 3000;
var connectionList = [];
server.listen(port, () => {
console.log("Server Started..")
})
const wss = new WebSocket.Server({
server,
path: "/ws"
});
wss.on("connection", function (ws, req) {
console.log("new Connection is coming..")
var roomId = querystring.parse(req.url.split("?")[1]).roomId;
if (connectionList[roomId] == undefined) {
connectionList[roomId] = [];
}
connectionList[roomId].push(ws);
console.log("room (" + roomId + ") has - " + connectionList[roomId].length + " connections")
sendConnectionStatus(roomId)
ws.on("message", function (msg) {
console.log("new msg ..")
var message = msg.toString("utf8");
broadCast(roomId, message);
})
ws.on("close", function () {
console.log("close connection")
disconnectConnections(roomId, ws)
console.log("room (" + roomId + ") has - " + connectionList[roomId].length + " connections")
sendConnectionStatus(roomId)
})
})
function sendConnectionStatus(roomId) {
var initMsg = {
"type": "info",
"count": connectionList[roomId].length
}
broadCast(roomId, JSON.stringify(initMsg));
}
function broadCast(roomId, message) {
if (connectionList[roomId] != undefined) {
try {
connectionList[roomId].forEach(function (conn, i) {
conn.send(message);
})
} catch (error) {
console.log(error);
}
}
}
function disconnectConnections(roomId, ws) {
connectionList[roomId].forEach(function (conn, i) {
if (conn === ws) {
connectionList[roomId].splice(i, 1);
}
});
}