-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathio.js
45 lines (34 loc) · 1.02 KB
/
io.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
module.exports = function(io){
io.sockets.on('connection', function(socket){
console.log("Cliente connected");
socket.on('set_nickname', function(nickname,
callback){
console.log('Trying to set nickname: ' + nickname);
var isAvailable = isNicknameAvailable(nickname);
if (isAvailable)
socket.nickname = nickname;
callback(isAvailable);
sendMessage("SERVER", "User @" + nickname + " has conected");
});
socket.on('message', function(message){
sendMessage(socket.nickname, message);
});
socket.on('disconnection', function(){
sendMessage("SERVER", "User @" + socket.nickname + " has disconnected.");
});
});
var sendMessage = function(nickname, message){
io.sockets.emit('message', nickname, message);
};
var isNicknameAvailable = function(nickname){
var clients = io.sockets.clients();
for (var client in clients){
if (clients.hasOwnProperty(client)){
client = clients[client];
if (client.nickname == nickname)
return false;
}
}
return true;
};
}