-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
81 lines (67 loc) · 2.2 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
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app, { log: false });
var fs = require('fs');
var sanitizer = require('sanitizer');
var users = [];
app.listen(8080);
console.log('>>> tinyChat started at port 8080 >>>');
function handler (req, res) {
fs.readFile(__dirname + '/client' + req.url,
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading requested file ' + req.url);
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
var myNick = 'guest';
var myColor = rndColor();
users.push({ id: socket.id, nick: myNick, color: myColor });
io.sockets.emit('userJoined', { nick: myNick, color: myColor });
io.sockets.emit('users', users);
socket.on('message', function (msg) {
var sanitizedMsg = sanitizer.sanitize(msg.text);
if(sanitizedMsg != msg.text) {
console.log('(!) Possible attack detected from ' + socket.id + ' (' + myNick + ') : ' + msg.text);
}
if(!sanitizedMsg || sanitizedMsg.length>256) {
return;
}
io.sockets.emit('message', { text: sanitizedMsg, color: myColor, nick: myNick });
});
socket.on('nickChange', function (user) {
var sanitizedNick = sanitizer.sanitize(user.nick);
if(sanitizedNick != user.nick) {
console.log('(!) Possible attack detected from ' + socket.id + ' (' + myNick + ') : ' + user.nick);
}
if(!sanitizedNick || myNick == sanitizedNick || sanitizedNick.length>32) {
return;
}
io.sockets.emit('nickChange', { newNick:sanitizedNick, oldNick: myNick, color: myColor });
myNick = sanitizedNick;
for(var i = 0; i<users.length; i++) {
if(users[i].id == socket.id) {
users[i].nick = myNick;
break;
}
}
io.sockets.emit('users', users);
});
socket.on('disconnect', function () {
io.sockets.emit('userLeft', { nick: myNick, color: myColor });
for(var i = 0; i<users.length; i++) {
if(users[i].id == socket.id) {
users.splice(i,1);
break;
}
}
io.sockets.emit('users', users);
});
function rndColor() {
var color = '#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6);
return color;
};
});