-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathechoServer.js
32 lines (27 loc) · 1.04 KB
/
echoServer.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
const net = require('net')
const port = 7070
const host = '127.0.0.1'
const server = net.createServer()
server.listen(port, host, () => {
console.log('TCP Server is running on port ' + port + '.')
})
let sockets = []
server.on('connection', function(sock){
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort)
sockets.push(sock)
sock.on('data', function(data){
console.log('DATA ' + sock.remoteAddress + ' : ' + data)
// Write the data back to all the connected, the client will receive it as data from the server
sockets.forEach(function (sock, index, array) {
sock.write(sock.remoteAddress + ':' + sock.remotePort + "said" + data + '\n')
})
})
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data){
let index = sockets.findIndex(function(o){
return o.remoteAddress === sock.remoteAddress && o.remotePort ===sock.remotePort
})
if(index !== -1) sockets.splice(index, 1)
console.log('CLOSED:' + sock.remoteAddress + ' ' + sock.remotePort)
})
})