In this guide, we will explore the powerful combination of Node.js and WebSockets for developing real-time web applications. We will delve into the fundamentals of WebSocket protocol, how it differs from traditional HTTP requests, and how to set up a Node.js server to handle WebSocket connections. By the end of this post, you will have built a simple chat application that exemplifies real-time communication between multiple users.
WebSocket is a communication protocol that provides full-duplex communication between the client and the server over a single, long-lived connection. Unlike traditional HTTP requests, which are unidirectional and require a new connection for each request, WebSocket connections allow bidirectional communication, making them perfect for real-time applications.
We will use the popular Node.js library ws to handle WebSocket connections on our server. To install it, run the following command in your terminal:
npm install ws
Next, we will create a simple WebSocket server that listens for connections and messages from clients.
// Importing the ws module
const WebSocket = require('ws');
// Creating a WebSocket server
const wss = new WebSocket.Server({ port: 8080 });
// Handling connection event
wss.on('connection', (ws) => {
console.log('New client connected');
// Handling message event
ws.on('message', (message) => {
console.log('Received:', message);
});
// Sending a message to the client
ws.send('Hello from server!');
});
Now that we have set up our WebSocket server, we can start building our chat application. We will create a simple HTML page with a text input and a button for sending messages, and a div element for displaying received messages.
<html>
<body>
<div id="messages"></div>
<input id="message-input" type="text">
<button id="send-button">Send</button>
</body>
</html>
On the client side, we will open a WebSocket connection to our server and handle the sending and receiving of messages.
// Opening a WebSocket connection
const ws = new WebSocket('ws://localhost:8080');
// Getting references to HTML elements
const messagesDiv = document.getElementById('messages');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
// Handling open event
ws.onopen = () => {
console.log('Connected to server');
};
// Handling message event
ws.onmessage = (event) => {
const message = event.data;
messagesDiv.innerHTML += '<p>' + message + '</p>';
};
// Sending a message to the server
sendButton.onclick = () => {
const message = messageInput.value;
ws.send(message);
messageInput.value = '';
};
Ready to start learning? Start the quest now