Last active
March 10, 2018 12:02
-
-
Save sadick254/5e00a0c5bab8deca315c859e2bcd8f14 to your computer and use it in GitHub Desktop.
A Simple TCP Chat Server In Node Js
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
//run this with 'node server.js' and then test in multiple computers using 'telnet 192.168.0.1 9000' | |
// replace '192.168.0.1' with your ip. | |
(function () { | |
'use strict'; | |
let net = require('net'); | |
let chatServer = net.createServer(), | |
clientList = []; // a list of connected clients/ machines | |
chatServer.on('connection', function (client) { | |
//once a client connects we add it to our clientList | |
clientList.push(client); | |
client.write('Connected \r\n'); | |
let message = ""; //holds chunks of the message being typed by a client until the user presses 'enter' | |
client.on('data', function (data) { | |
// since tcp sends every character in its own request we have to store every character typed in the message variable | |
message += data; | |
clientList.forEach(function (clientConnected) { | |
//display message to all connected clients except the current client typing. We do this to avoid double display | |
//of the typed message to the current client typing; | |
if (clientConnected !== client) { | |
// only sending data when the 'enter' key is pressed. '0d0a' is the hexadecimal representation of 'enter' key | |
if (data.toString('hex') === '0d0a') { | |
clientConnected.write(message); | |
// after sending the message reset it back to blank. | |
message = ""; | |
} | |
} | |
}); | |
}); | |
// when a client leaves the chat we have to remove it from our list to avoid sending messages to unexisting client | |
//which raises errors | |
client.on('end',function(){ | |
clientList.splice(clientList.indexOf(client),1); | |
}); | |
}); | |
chatServer.listen(9000); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment