-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.js
More file actions
132 lines (93 loc) · 2.63 KB
/
Copy pathchat.js
File metadata and controls
132 lines (93 loc) · 2.63 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*****************************
Configurations
*****************************/
var globals = {
'port': 8337,
'password': 'pakrox'
};
/*****************************
Includes
*****************************/
net = require("net");
/*****************************
Snippets
*****************************/
// From http://snippets.dzone.com/posts/show/701
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/, '');
};
/*****************************
Classes
*****************************/
function User(socket) {
this.socket = socket;
this.username = 'anonymous';
// current defined states are:
// login, identify, ok
this.state = 'login';
this.init();
}
User.prototype = {
init: function() {
this.socket.setEncoding("utf8");
},
identify: function(username) {
this.username = username;
}
};
// pretty print (singleton)
var PP = {
msg: function(username, text) {
return this.user(username) + " " + text.trim() + "\n";
},
user: function(username) {
return "<" + username + ">";
}
};
/*****************************
Server Stuff
*****************************/
var users = [];
function broadcast(fullmsg, currentuser) {
users.forEach(function(someuser) {
if (someuser == currentuser || someuser.state != "ok")
return;
someuser.socket.write(fullmsg);
});
}
var s = net.Server(function(socket) {
var user = new User(socket);
users.push(user);
socket.on('connect', function() {
socket.write("Enter the password: ");
});
socket.on('data', function(data) {
if (user.state == 'login') {
data = data.trim();
if (data == globals.password) {
socket.write("Enter your username: ");
user.state = "identify";
} else {
socket.destroy();
}
return;
}
if (user.state == 'identify') {
var username = data.trim();
user.identify(username);
socket.write("==> Congratulations! You are now logined!\n");
broadcast("^_^ `" + user.username + "` has just logined\n", user);
user.state = "ok";
return;
}
// the `ok` state
broadcast(PP.msg(user.username, data), user)
});
socket.on('end', function() {
broadcast("^_^ `" + user.username + "` has left the conversation\n", user);
var i = users.indexOf(user);
users.splice(i, 1);
});
});
s.listen(globals.port);
console.log("Chat server started on port " + globals.port);