-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatServer.js
41 lines (32 loc) · 1002 Bytes
/
chatServer.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
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');
console.log(client.name + ' joined')
clientList.push(client)
client.on('data', function(data) {
broadcast(data, client)
})
client.on('end', function(data) {
console.log(client.name + ' quit')
clientList.splice(clientList.indexOf(client), 1)
})
client.on('error', function(e) {
console.log(e)
})
})
function broadcast(message, client) {
for(var i=0;i<clientList.length;i+=1) {
if(client !== clientList[i]) {
if(clientList[i].writable) {
clientList[i].write(client.name + " says " + message)
} else {
cleanup.push(clientList[i])
clientList[i].destroy()
}
}
}
}
chatServer.listen(9000)