-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
43 lines (32 loc) · 791 Bytes
/
chat.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
var net = require('net');
var carrier = require('carrier');
var connections = [];
net.createServer(function(conn) {
connections.push(conn);
conn.write("Hello, welcome to this chat server!\n");
conn.write("Please input your user name: \n");
conn.on('close', function() {
var pos = connections.indexOf(conn);
if(pos >= 0) {
connections.splice(pos, 1);
}
});
var username;
carrier.carry(conn, function(line) {
if(!username) {
username = line;
conn.write("Hello " + username + "!\n");
return;
}
if(line == 'quit') {
conn.end();
return;
}
var feedback = username + ": " + line + "\n";
connections.forEach(function(one_connection) {
one_connection.write(feedback);
})
});
conn.on('data', function(data) {
});
}).listen(4000);