Created
July 21, 2018 16:07
-
-
Save wesdeveloper/c2212e52b0a354d4025f443b11099d47 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const server = require('net').createServer(); | |
const sockets = {}; | |
let counter = 0; | |
server.on('connection', socket => { | |
socket.id = counter++; | |
console.log('Client connected!'); | |
socket.write('Please type your name: '); | |
socket.on('data', data => { | |
if(!sockets[socket.id]) { | |
socket.name = data.toString().trim(); | |
socket.write(`Welcome ${socket.name}!\n`); | |
sockets[socket.id] = socket; | |
return; | |
} | |
Object.entries(sockets).forEach(([key, cs]) => { | |
const text = socket.id == key ? 'me' : socket.name; | |
cs.write(`${text}: `); | |
cs.write(data); | |
}); | |
}); | |
socket.on('end', () => { | |
console.log(`Cliente ${socket.name} desconected!`); | |
delete sockets[socket.id]; | |
}) | |
}); | |
server.listen(3000, () => | |
console.log('Server listening at port 3000')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment