Welcome to our comprehensive guide on building a WebSocket server using Node.js! In this tutorial, we will learn what WebSockets are, why they are important, and how to create a real-time chat application as a practical example.
WebSockets provide a full-duplex communication channel over a single TCP connection. Unlike traditional HTTP requests, which are half-duplex (request-response), WebSockets allow for real-time, bidirectional communication between the client and server.
WebSockets are essential for building real-time web applications, such as chat applications, live game updates, and interactive dashboards. They offer a low-latency, efficient, and seamless user experience compared to polling techniques, which refresh the page periodically to check for updates.
To follow along, ensure you have Node.js installed on your machine. You can download it from the official website: Node.js.
Once Node.js is installed, open a terminal, and install the required package: ws, which is a simple WebSocket library for Node.js.
npm install wsNow let's create a simple chat application that allows multiple users to send and receive messages in real-time.
Create a new file called server.js and paste the following code:
const WebSocket = require('ws');
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
res.writeHead(200);
res.end('Node.js WebSocket Chat Server');
});
// Create the WebSocket server
const wss = new WebSocket.Server({ server });
wss.on('connection', (socket) => {
console.log('Client connected');
// Broadcast messages to all clients
const broadcast = (data) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
// Handle messages from clients
socket.on('message', (message) => {
console.log(`Received: ${message}`);
broadcast(message);
});
// Handle client disconnection
socket.on('close', () => {
console.log('Client disconnected');
});
});
// Start the server
server.listen(3000, () => {
console.log('Server listening on port 3000');
});Next, create a new HTML file called index.html with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>
<body>
<h1>Node.js WebSocket Chat</h1>
<ul id="messages"></ul>
<form id="chat-form">
<input type="text" id="message" placeholder="Type your message here...">
<button type="submit">Send</button>
</form>
<script>
const messages = document.getElementById('messages');
const chatForm = document.getElementById('chat-form');
const messageInput = document.getElementById('message');
const socket = new WebSocket('ws://localhost:3000');
// Connection opened
socket.addEventListener('open', (event) => {
console.log('Connected to WebSocket server');
});
// Listen for messages from server
socket.addEventListener('message', (event) => {
const li = document.createElement('li');
li.textContent = event.data;
messages.appendChild(li);
});
// Send messages to server
chatForm.addEventListener('submit', (event) => {
event.preventDefault();
if (messageInput.value) {
socket.send(messageInput.value);
messageInput.value = '';
}
});
</script>
</body>
</html>To run the application, save both files in the same directory, and start the server by running node server.js in your terminal. Open multiple browser windows or tabs and navigate to http://localhost:3000. You should now be able to send and receive messages in real-time!
What is the purpose of WebSockets in web development?