Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A simple TCP based chat server written in node.js
// Load the TCP Library
net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function (socket) {
// Identify this client = socket.remoteAddress + ":" + socket.remotePort
// Put this new client in the list
// Send a nice welcome message and announce
socket.write("Welcome " + + "\n");
broadcast( + " joined the chat\n", socket);
// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast( + "> " + data, socket);
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast( + " left the chat.\n");
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
// Don't want to send it to sender
if (client === sender) return;
// Log it to the server output too
// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");
Copy link

I was implementing this then I ran across this Gist.
see here

Copy link

adrwh commented Feb 17, 2019

This is cool, can it be re-written to use pipe() instead of listening to events?

Copy link

TeSsErAcT25 commented Jun 21, 2019

To All those who are complaining That this code is buggy
This is only the server code
You have to write the Client code by yourself to make this run properly
Here is a simple Client Code

var net = require('net')
var client = net.connect({port : 5000},function(){
    console.log('connected to the server')

client.write("Hello !!!!")

Copy link

Also note that this code was written almost a decade ago! The node.js APIs and best practices have changed significantly since then.

Copy link

ahmednawazkhan commented Oct 2, 2019

Hi. I just want to open a socket that accepts tcp traffic. and when I telnet to that port I get notified ( may be console.log ). Is it even possible to telnet into a opened socket?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment