-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
executable file
·88 lines (66 loc) · 2.32 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
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var userList = new Map();
var cc = 0;
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + ' Server is listening on port 8080');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
});
function originIsAllowed(origin) {
return true;
}
wsServer.on('request', function(request) {
if (!originIsAllowed(request.origin)) {
request.reject();
console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
return;
}
var connection = request.accept(null, request.origin);
connection.cc = cc;
cc += 1;
userList.set(connection.cc, {connection: connection, user: ''});
console.log((new Date()) + ' Connection accepted.');
connection.on('message', function(message) {
obj = JSON.parse(message.utf8Data);
if (obj.type == 'join') {
u = userList.get(connection.cc);
u.user = obj.user;
let listOrdered = [];
userList.forEach(function (v, k) {
listOrdered.push(v.user);
});
listOrdered.sort();
userList.forEach(function(v, k) {
v.connection.send(JSON.stringify({ type: 'updateUserList', user: obj.user, content: listOrdered }));
v.connection.send(JSON.stringify({ type: 'joined', user: obj.user, content: '' }));
});
}
if (obj.type == 'message') {
userList.forEach(function(v, k) {
v.connection.send(JSON.stringify(obj));
});
}
});
connection.on('close', function(reasonCode, description) {
let u = userList.get(connection.cc);
userList.delete(connection.cc);
let listOrdered = [];
userList.forEach(function (v, k) {
listOrdered.push(v.user);
});
listOrdered.sort();
userList.forEach(function(v, k) {
v.connection.send(JSON.stringify({ type: 'updateUserList', user: u.user, content: listOrdered }));
v.connection.send(JSON.stringify({ type: 'left', user: u.user, content: '' }));
});
});
});