-
Notifications
You must be signed in to change notification settings - Fork 1
/
chat.js
46 lines (36 loc) · 1.03 KB
/
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
44
45
46
var net = require('net');
var chatServer = net.createServer(),
clientList = [];
chatServer.on('connection', function(client){
client.name = client.remoteAddress + ':' + client.remotePort;
client.write('Hi ' + client.name + '\n');
clientList.push(client);
client.on('data', function (data){
broadcast(data, client);
});
client.on('end', function () {
// коли клієт відключився видаляємо його з масиву clientList
clientList.splice(clientList.indexOf(client), 1);
});
client.on('error', function(e) {
console.log(e);
});
function broadcast(message, client){
var cleanup = [];
for (var i = 0; i < clientList.length; i++) {
if (client !== clientList[i]) {
if (clientList[i].writable) {
clientList[i].write(client.name + ' says: ' + message);
}
else {
cleanup.push(clientList[i]);
clientList[i].destroy();
}
}
}
for (var i = 0; i < cleanup.length; i++) {
clientList.splice(clientList.indexOf(cleanup[i]), 1);
}
}
})
chatServer.listen(9000);