Skip to content

Instantly share code, notes, and snippets.

@SarasArya
Created April 2, 2017 08:58
Show Gist options
  • Save SarasArya/d8ad610679122becc642104ac29d98b9 to your computer and use it in GitHub Desktop.
Save SarasArya/d8ad610679122becc642104ac29d98b9 to your computer and use it in GitHub Desktop.
A chat server built purely in NodeJS without the socket.io module. Will help you chat with your roomates on the same router.
process.stdout.write('\u001B[2J\u001B[0;0f'); // Cleans up the console.
const server = require('net').createServer();
let counter = 0;
let sockets = {};
//function to return the current time
let timeStamp = () => {
let now = new Date();
return `${now.getHours()}:${now.getMinutes()}`
};
server.on('connection', socket => { //here sockets is an EventEmitter
socket.id = counter++;
console.log('Client Connected');
socket.write("Please type your name: \n"); //A welcome message
socket.on('data', data => {
if (!sockets[socket.id]) { //To not echo the same message to you
socket.write(`Welcome aboard ${data}`);
socket.name = data.trim("\n");
sockets[socket.id] = socket;
return;
}
Object.entries(sockets).forEach(([key, cs]) => { //This will broadcast message to all the people connected to the server
// console.log(socket.id,+key);
if (socket.id === +key) { //The key is actually a `string number` To convert a string number into a number I used the + operator, It converted my string number to key to number
return;
} else {
cs.write(`${socket.name} @ ${timeStamp()} : `);
cs.write(`${data}`);
}
})
});
socket.on('end', () => {
delete sockets[socket.id];
console.log('Client Disconnected'); //Show the nessage when a client disconnects
});
socket.setEncoding('utf8'); //Set the encoding to whatever you like
});
server.listen(8000, () => { //Appliation listening on port 8000
console.log('Server bound');
})
//To run this code open a terminal in Mac/Ubuntu and type nc localhost 8000 and see the magic. You can also type the local IP and chat with people probably on the same router.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment