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
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);
});
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);
});
}
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
Terminal 2 (Client 1):
node client.js
Terminal 3 (Client 2):
node client.js
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)