Last active
May 31, 2020 17:57
-
-
Save ecavalcanti/56b9f2e31c3db6a067819cdabbdb9808 to your computer and use it in GitHub Desktop.
Simple Node Socket Server
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 net = require('net'); | |
const hostname = process.env.SERVER_HOSTNAME || '0.0.0.0'; | |
const port = process.env.SERVER_PORT || 8124; | |
const interval = process.env.INTERVAL || 1000; | |
const plates = process.env.PLATES ? process.env.PLATES.split(',') : undefined; | |
const sockets = []; | |
const server = net.createServer((socket) => { | |
const clientAddress = `${socket.remoteAddress}:${socket.remotePort}`; | |
console.log(`new client connected: ${clientAddress}`); | |
socket.on('data', data => { | |
console.log(`Receive data: ${data}`); | |
}); | |
socket.on('close', () => { | |
const index = sockets.findIndex((o) => { | |
return (o.remoteAddress === socket.remoteAddress) && | |
(o.remotePort === socket.remotePort); | |
}); | |
if (index !== -1) sockets.splice(index, 1); | |
console.log(`connection closed: ${clientAddress}`); | |
}); | |
socket.on('error', (err) => { | |
console.log(`Error occurred in ${clientAddress}: ${err.message}`); | |
}); | |
sockets.push(socket); | |
}).on('error', (err) => { | |
// Handle errors here. | |
throw err; | |
}); | |
setInterval(() => { | |
sockets.forEach(socket => { | |
const plate = generatePlate(); | |
socket.write(`${plate},https://dummyimage.com/600x400/32b85c/fff.jpg&text=${plate}` + '\n'); | |
}); | |
}, interval); | |
server.listen(port, hostname, () => { | |
console.log('opened server on', server.address()); | |
}); | |
const generatePlate = () => { | |
if (plates) { | |
const index = Math.floor(Math.random() * plates.length); | |
return plates[index]; | |
} else { | |
return generateLetters(3).toUpperCase() + (Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000) | |
} | |
} | |
const generateLetters = (len) => { | |
let text = ''; | |
const charset = 'abcdefghijklmnopqrstuvwxyz'; | |
for (let i = 0; i < len; i++) { | |
text += charset.charAt(Math.floor(Math.random() * charset.length)); | |
} | |
return text; | |
} | |
const randomInt = (min, max) => { | |
return min + Math.floor((max - min) * Math.random()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment