forked from rodrigoms2004/ServerSocketTCP_UDP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp_server.js
69 lines (55 loc) · 1.89 KB
/
tcp_server.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const net = require('net')
const conf = require('./config/config')
const {
log
} = require('./util/loggerTool')
const server = net.createServer()
// emits when any error occurs
server.on('error', (error) => {
log("tcp_server", "error", error)
server.close()
})
const sockets = []
server.on('connection', sock => {
log("tcp_server", "info", `Connected at ${sock.remoteAddress}:${sock.remotePort}`)
sockets.push(sock)
sock.on('data', data => {
log("tcp_server", "info", data.toString() + ` | Received ${sock.bytesRead} bytes from ${sock.remoteAddress}:${sock.remotePort}`)
let timestp = new Date()
const response = {
description: 'TCP PORT TEST BY RMS Math',
serverPort: conf.port,
timestamp: timestp.toJSON(),
received: {
message: data.toString(),
fromIP: sock.remoteAddress,
fromPort: sock.remotePort
}
}
const dataBuffer = Buffer.from(JSON.stringify(response))
// Write the data back to all the connected, the client will receive it as data from the server
sockets.forEach((sock, index, array) => {
sock.write(dataBuffer)
})
})
// Add a 'close' event handler to this instance of socket
sock.on('close', data => {
let index = sockets.findIndex( o => {
return o.remoteAddress === sock.remoteAddress && o.remotePort === sock.remotePort
})
if (index !== -1) {
sockets.splice(index, 1)
}
log("tcp_server", "info", `Socket closed with ${sock.remoteAddress}:${sock.remotePort}`)
}) // end sock.on
})
// server.listen(conf.port, conf.serverHost, () => {
server.listen(conf.port, conf.serverHost, () => {
const address = server.address()
const port = address.port
const family = address.family
const ipaddr = address.address
log("tcp_server", "info", 'Server is listening at port ' + port)
log("tcp_server", "info", 'Server ip :' + ipaddr)
log("tcp_server", "info", 'Server is IP4/IP6 : ' + family)
}) // server.listen()