DEV Community

Cover image for Build Your First TCP Chat App Using Node.js ๐Ÿš€๐Ÿ’ฌ
Avijit Bera
Avijit Bera

Posted on

Build Your First TCP Chat App Using Node.js ๐Ÿš€๐Ÿ’ฌ

Are you prepared to explore the realm of real-time communication and networking? We'll use Node.js to create a straightforward yet effective TCP chat application in this step-by-step tutorial! ๐ŸŒŸ

What is TCP? ๐Ÿค”
One of the primary protocols in the Internet protocol suite is TCP (Transmission Control Protocol). It guarantees data transport between applications operating on hosts interacting via an IP network in a dependable, organised, and error-checked manner. Consider it your data's trustworthy postal service! ๐Ÿ“ฎ

Prerequisites ๐Ÿ› ๏ธ
Before we start, make sure you have:

  • Node.js installed on your machine
  • A code editor (VS Code recommended)
  • Basic JavaScript knowledge
  • Terminal/Command Prompt access

Step 1: Setting Up the Project ๐Ÿ“
First, let's create our project directory and initialize it:

mkdir tcp-chat-app
cd tcp-chat-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

That's it! We don't need any external dependencies since Node.js has built-in modules for TCP networking. ๐ŸŽ‰

Step 2: Creating the TCP Server ๐Ÿ–ฅ๏ธ
Create a file called server.js and let's build our chat server:

// server.js
const net = require('net');

// Array to store all connected clients
const clients = [];

// Create TCP server
const server = net.createServer((socket) => {
    console.log('โœจ New client connected!');

    // Add new client to our list
    clients.push(socket);

    // Set encoding for received data
    socket.setEncoding('utf8');

    // Send welcome message to new client
    socket.write('๐ŸŽ‰ Welcome to the TCP Chat Server!\n');
    socket.write('๐Ÿ’ฌ Start typing to chat with others...\n\n');

    // Broadcast message to all clients when someone sends a message
    socket.on('data', (data) => {
        const message = data.toString().trim();
        if (message) {
            console.log(`๐Ÿ“จ Message received: ${message}`);
            broadcast(`${socket.remoteAddress}: ${message}`, socket);
        }
    });

    // Handle client disconnection
    socket.on('end', () => {
        console.log('๐Ÿ‘‹ Client disconnected');
        const index = clients.indexOf(socket);
        if (index !== -1) {
            clients.splice(index, 1);
        }
    });

    // Handle errors
    socket.on('error', (err) => {
        console.log('โŒ Client error:', err.message);
    });
});

// Function to broadcast messages to all clients except the sender
function broadcast(message, sender) {
    clients.forEach((client) => {
        if (client !== sender && !client.destroyed) {
            client.write(`๐Ÿ“ข ${message}\n`);
        }
    });
}

// Start the server
const PORT = 3000;
const HOST = 'localhost';

server.listen(PORT, HOST, () => {
    console.log(`๐Ÿš€ TCP Chat Server running on ${HOST}:${PORT}`);
    console.log('โณ Waiting for clients to connect...');
});

// Handle server errors
server.on('error', (err) => {
    console.log('โŒ Server error:', err.message);
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating the TCP Client ๐Ÿ“ฑ
Now, create a file called client.js for our chat client:

// client.js
const net = require('net');
const readline = require('readline');

// Create interface for reading user input
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

// Create TCP client
const client = new net.Socket();

// Connect to server
const PORT = 3000;
const HOST = 'localhost';

client.connect(PORT, HOST, () => {
    console.log('โœ… Connected to chat server!');
    console.log('๐Ÿ’ฌ Type your messages and press Enter to send');
    console.log('โน๏ธ  Type "exit" to quit\n');

    // Prompt for first message
    promptUser();
});

// Handle data received from server
client.on('data', (data) => {
    console.log(data.toString());
    promptUser();
});

// Handle connection close
client.on('close', () => {
    console.log('๐Ÿ”Œ Connection closed');
    rl.close();
});

// Handle errors
client.on('error', (err) => {
    console.log('โŒ Connection error:', err.message);
    rl.close();
});

// Function to prompt user for input
function promptUser() {
    rl.question('', (message) => {
        if (message.toLowerCase() === 'exit') {
            console.log('๐Ÿ‘‹ Goodbye!');
            client.end();
            rl.close();
            return;
        }

        // Send message to server
        client.write(message);
    });
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Understanding the Code ๐Ÿง 
Let's break down what we've built:

Server Breakdown:

  • Server Creation ๐Ÿ—๏ธ: We use net.createServer() to create a TCP server
  • Client Management ๐Ÿ‘ฅ: We store all connected clients in an array
  • Message Broadcasting ๐Ÿ“ข: When a client sends a message, we forward it to all other clients
  • Event Handling โšก: We handle connection, data reception, disconnection, and errors

Client Breakdown:

  • Connection Setup ๐Ÿ”Œ: The client connects to our server using net.Socket()
  • User Input โŒจ๏ธ: We use readline to get input from the user
  • Message Display ๐Ÿ“บ: We show messages received from the server
  • Graceful Exit ๐Ÿšช: Users can type "exit" to quit the chat

Step 5: Running the Chat App ๐Ÿƒโ€โ™‚๏ธ
Let's test our application! Open two terminal windows:

Terminal 1 (Server):

node server.js
Enter fullscreen mode Exit fullscreen mode

Terminal 2 (Client 1):

node client.js
Enter fullscreen mode Exit fullscreen mode

Terminal 3 (Client 2):

node client.js
Enter fullscreen mode Exit fullscreen mode

Now you can send messages between clients! ๐ŸŽŠ

Step 6: Testing the Application ๐Ÿงช

  • Start the server in one terminal
  • Open multiple client terminals
  • Send messages from different clients
  • Watch the real-time magic happen! โœจ

Common Issues and Solutions ๐Ÿ”ง

  • Port Already in Use โŒ: Change the PORT number in both files
  • Connection Refused ๐Ÿ”Œ: Make sure the server is running first
  • Cannot Type Messages โŒจ๏ธ: The readline interface might be blocked

Conclusion ๐ŸŽ‰
Congratulations! ๐Ÿฅณ You've just built a functional TCP chat application using Node.js. You learned:

  • โœ… How TCP networking works
  • โœ… How to create TCP servers and clients
  • โœ… Real-time message broadcasting
  • โœ… Handling multiple client connections
  • โœ… Basic networking concepts

Top comments (0)