-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
81 lines (70 loc) · 1.78 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
/**
* @author Crysfel Villa
* @date Jan 6, 2011
*
**/
var http = require('http'),
sys = require('sys'),
fs = require('fs'),
io = require('socket.io'),
Connect = require('connect');
var Server = {
init : function(){
var me = this;
this.server = Connect.createServer(
Connect.logger(), // Log responses to the terminal using Common Log Format.
Connect.static(__dirname + "/webapp") // Serve all static files in the current dir.
);
this.socket = io.listen(this.server);
this.socket.addListener("connection", function(client){
me.onConnection(client);
});
},
start : function(port){
this.server.listen(port);
console.log("Server started at 8080");
},
onConnection : function(client) {
var user,
me = this;
client.addListener("message", function(message) {
if (!user) {
user = message;
Chat.userMap[user.username] = {username:user.username,email:user.email};
client.send({ message: 'Server: Welcome, ' + user.username + '! please be nice with other people.', username: 'Server', email: '' });
me.socket.broadcast({
users : Chat.getUsers(),
updateList : true
});
return;
}
var response = {
"username" : user.username,
"email" : user.email,
"message" : message.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")
};
me.socket.broadcast(response);
});
client.addListener("disconnect",function(){
if(user && user.username){
delete Chat.userMap[user.username];
me.socket.broadcast({
users : Chat.getUsers(),
updateList : true
});
}
});
}
}
var Chat = {
userMap: {},
getUsers : function(){
var list = [];
for(var key in this.userMap){
list.push(this.userMap[key]);
}
return list;
}
}
Server.init();
Server.start(process.env.PORT || 8001);