-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
90 lines (68 loc) · 2.14 KB
/
server.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const http = require("http");
const qs = require("querystring");
const express = require("express");
const PORT = process.env.PORT || 3000;
const INDEX = 'index.html';
const server = express()
.use(express.static(__dirname + '/'))
.listen(PORT, () => console.log(`Listening on ${PORT}`));
const { Server } = require('ws')
const wss = new Server({ server });
var chat = [];
var users = [];
wss.on('connection', ws => {
console.log("Connected to server.");
if(chat.length) {
console.log("Updating chat...");
ws.send(JSON.stringify(chat));
}
ws.on('message', message => {
const data = JSON.parse(message.toString());
switch(data.type)
{
case "message":
console.log("Received message, sending to client...", data);
chat.push(data);
ws.send(JSON.stringify(chat));
console.log("Sending chat to all other clients...");
wss.clients.forEach(client => {
console.log(client.readyState);
if(client!==ws /*&& client.readyState===Server.OPEN*/)
client.send(JSON.stringify(chat));
});
break;
case "login":
console.log("User connected.. Sending to client...", data);
users.push(data);
ws.send(JSON.stringify(users));
console.log("Sending new connect to other clients..");
wss.clients.forEach(client => {
console.log(client.readyState);
if(client!==ws /*&& client.readyState===Server.OPEN*/)
client.send(JSON.stringify(users));
});
break;
case "exit":
console.log("User disconnected.. Sending to client...", data);
users.splice(users.findIndex(element => element.user == data.user),1);
ws.send(JSON.stringify(users));
console.log("Sending D/C to other clients..");
wss.clients.forEach(client => {
console.log(client.readyState);
if(client!==ws /*&& client.readyState===Server.OPEN*/)
client.send(JSON.stringify(users));
});
break;
case "ping":
console.log("Updating User list, ping received from ", data.user);
users.splice(users.findIndex(element => element.user == data.user),1);
console.log("debug:", users);
users.push(data);
console.log("debug 2:",users)
ws.send(JSON.stringify(users));
break;
}
});
});
wss.on("close", ws => {
});