forked from ordinerf/nodejschat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
55 lines (49 loc) · 1.86 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
var html = require('fs').readFileSync(__dirname+'/index.html');
var server = require('http').createServer(function(req, res){
res.end(html);
});
server.listen(1337);
var nowjs = require("now");
var everyone = nowjs.initialize(server);
var clients = {}; // Attention ne pas initialiser avec [] car bug lors de la transmission de la variable au client
everyone.now.newClient = function(name){
//On ajoute le client au tableau en renseignant son pseudo et son statut (connecté ou non)
clients[this.user.clientId] = { login: name, statut: 1};
// On met à jour la liste des connectés
for(var c in clients) {
nowjs.getClient(c, function(err) {
this.now.updateClientList(clients);
});
}
};
everyone.now.openChat = function(idClient){
var idChat = idClient+this.user.clientId;
var newChat = nowjs.getGroup(idChat);
newChat.addUser(this.user.clientId);
newChat.addUser(idClient);
newChat.now.addChat(idChat,idClient,clients[idClient].login,clients[this.user.clientId].login);
};
everyone.now.sendMessage = function(message, room){
var group = nowjs.getGroup(room);
var idSender = this.user.clientId;
group.count(function (ct) {
if(ct <= 1) group.now.displayMessage(room, "Your friend isn't connected");
else group.now.displayMessage(room, clients[idSender].login+': '+clean(message));
});
};
nowjs.on('disconnect', function() {
for(var i in clients) {
if(i == this.user.clientId) {
delete clients[i];
break;
}
}
for(var i in clients) {
nowjs.getClient(i, function(err) {
this.now.updateClientList(clients);
});
}
});
function clean(html){
return String(html).replace(/&(?!\w+;)/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}