-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
44 lines (38 loc) · 1.35 KB
/
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
const net = require('net');
const port = 8080
const clientList = []
const server = net.createServer((socket) => {
console.log('opened connection', socket.remoteAddress, socket.remotePort)
clientList.push(socket)
socket.username = socket.remotePort + ' '
socket.on('data', (data) => {
const first = String(data).split(' ')[0]
message = String(data).replace(first + " ", '').trim()
if (first == 'SEND') {
clientList.forEach((client) => {
if (client != socket) {
client.write('RECEIVE ' + socket.username + message + '\n')
}
})
} else if (first == 'USERNAME') {
if (message.indexOf(' ') !== -1) {
socket.write('ERROR invalid username\n')
} else {
socket.username = message + ' '
}
} else {
if (String(data) == 'USERNAME\n') {
socket.write('USERNAME -> ' + socket.username + '\n')
} else {
socket.write('ERROR invalid command\n')
}
}
})
socket.on('close', () => {
clientList.splice(clientList.indexOf(socket), 1)
console.log('closed connection', socket.remoteAddress, socket.remotePort)
})
})
server.listen(port, () => {
console.log('opened server on', server.address());
});