Project: WebSocket Chat Server
In this project, we will build a real-time, multi-client chat server using the native Node.js net module (TCP sockets). Clients will connect to the server using standard terminal tools like Telnet or Netcat.
1. Project Specifications
- Protocol: TCP Socket connections handled by Node.js
netmodule. - Broadcasting: Every incoming message from a client is broadcasted to all other active sockets.
- Events: Handle new connections, client exits, and system errors without crashing.
2. Implementing the TCP Chat Server
Create a new file named chatServer.js and paste the following implementation:
import net from "net";
// Store all active client sockets
const clients = new Set();
const server = net.createServer((socket) => {
// Set encoding to read string input instead of raw Buffers
socket.setEncoding("utf8");
// Add the new client connection to the active list
clients.add(socket);
const clientAddress = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`[JOIN] New client connected from ${clientAddress}`);
socket.write("Welcome to the Node.js TCP Chat Room!\n");
broadcast(`[SYSTEM] User from ${clientAddress} has joined the room.\n`, socket);
// Listen for incoming messages from this client
socket.on("data", (message) => {
const cleanMessage = message.trim();
if (cleanMessage) {
console.log(`[MSG] ${clientAddress}: ${cleanMessage}`);
broadcast(`[${clientAddress}]: ${cleanMessage}\n`, socket);
}
});
// Handle client disconnection
socket.on("end", () => {
clients.delete(socket);
console.log(`[LEAVE] Client ${clientAddress} disconnected`);
broadcast(`[SYSTEM] User from ${clientAddress} has left the room.\n`);
});
// Handle connection errors
socket.on("error", (err) => {
clients.delete(socket);
console.log(`[ERROR] Connection error for ${clientAddress}: ${err.message}`);
});
});
// Broadcast helper function to send messages to all active clients
function broadcast(message, senderSocket = null) {
for (const client of clients) {
// Write message to everyone except the sender
if (client !== senderSocket && client.writable) {
client.write(message);
}
}
}
const PORT = 4000;
server.listen(PORT, () => {
console.log(`TCP Chat Server is running on port ${PORT}`);
});3. Running and Testing the Server
First, launch the server in your terminal:
# Start the TCP chat server
node chatServer.jsNext, open multiple separate terminal windows to simulate different users connecting via Netcat (nc) or Telnet:
# User 1 connection
nc localhost 4000
# User 2 connection (in a separate terminal)
nc localhost 4000When User 1 types a message and presses Enter, it will immediately broadcast to the User 2 terminal, creating a real-time terminal chat room.
Published on Last updated: