-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
78 lines (65 loc) · 2.28 KB
/
server.js
File metadata and controls
78 lines (65 loc) · 2.28 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
74
75
76
77
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server,
wss = new WebSocketServer({port:8080});
var uuid = require('node-uuid');
var clients = [];
function wsSend(type, client_uuid, nickname, message){
for (var i=0; i<clients.length; i++) {
var clientSocket = clients[i].ws;
if (clientSocket.readyState === WebSocket.OPEN) {
clientSocket.send(JSON.stringify({
"type": type,
"id" : client_uuid,
"nickname": nickname,
"message": message
}));
}
}
} // end of func wsSend
var clientIndex = 1;
wss.on('connection', function(ws) {
var client_uuid = uuid.v4();
var nickname = "Joymonk "+clientIndex;
clientIndex+=1;
clients.push({"id": client_uuid, "ws": ws, "nickname": nickname});
console.log('client [%s] connected', client_uuid);
var connect_message = nickname + " has connected";
wsSend("notification", client_uuid, nickname, connect_message);
ws.on('message', function(message) {
var msg = JSON.parse(message);
if (msg.message.indexOf('/nick') === 0) {
var nickname_array = msg.message.split(' ');
if (nickname_array.length >=2) {
var old_nickname = nickname;
nickname = nickname_array[1];
msg.nickname_message = "Client "+old_nickname+" changed to "+nickname;
wsSend("nick_update", client_uuid, nickname, msg.nickname_message);
}
} else {
// wsSend("message", client_uuid, nickname, msg.message);
wsSend("message", client_uuid, nickname, msg);
}
});
var closeSocket = function(customMessage) {
for (var i=0; i<clients.length; i++) {
if (clients[i].id == client_uuid) {
var disconnect_message;
if (customMessage){
disconnect_message= customMessage;
} else {
disconnect_message = nickname + " has disconnected";
}
wsSend("notification", client_uuid, nickname, disconnect_message);
clients.splice(i,1);
}
}
}
ws.on('close', function() {
closeSocket();
});
process.on('SIGINT', function() {
console.log('Closing things...\n');
closeSocket('Server had disconnected\n');
process.exit();
});
});