Real-Time Applications in JavaScript with WebSockets
WebSockets enable seamless, real-time communication between a client and a server. Unlike traditional HTTP requests, WebSockets keep the connection open, making them perfect for dynamic and real-time applications like chat apps, live updates, and multiplayer games.
In this blog, you’ll learn how to set up WebSockets for real-time communication with detailed steps, code examples, and explanations.
Requirements
Before we begin, ensure you have the following:
- Node.js installed (version 12 or later recommended).
- A basic understanding of JavaScript and Node.js.
- A text editor like VS Code.
Steps for Installation
1. Initialize Your Project
Create a project directory and initialize it with npm
.
mkdir websocket-chat-app
cd websocket-chat-app
npm init -y
2. Install Dependencies
Install the ws
package for WebSocket support.
npm install ws
Implementation
1. Setting Up the WebSocket Server
File path: server/index.js
const WebSocket = require('ws');
// Create a WebSocket server
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
console.log('A client connected.');
// Handle incoming messages
socket.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast the message to all clients
server.clients.forEach((client) => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Handle disconnection
socket.on('close', () => {
console.log('A client disconnected.');
});
});
console.log('WebSocket server is running on ws://localhost:8080');
2. Setting Up the Client
File path: client/js/app.js
const socket = new WebSocket('ws://localhost:8080');
// Listen for incoming messages
socket.onmessage = (event) => {
const message = event.data;
console.log(`Message from server: ${message}`);
};
// Send a message to the server
document.getElementById('sendBtn').addEventListener('click', () => {
const input = document.getElementById('messageInput').value;
socket.send(input);
});
3. HTML for the Client
File path: client/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chat</title>
</head>
<body>
<h1>WebSocket Chat App</h1>
<input type="text" id="messageInput" placeholder="Type a message">
<button id="sendBtn">Send</button>
<script src="./js/app.js"></script>
</body>
</html>
Explanation
1. WebSocket Server (server/index.js
)
The WebSocket server acts as the backbone of your real-time application. Here’s how it works:
- Initializing the Server:
- A WebSocket server is created using the
ws
library. - The server listens for client connections on port
8080
. - Once the server is running, it will continuously listen for client requests.
- A WebSocket server is created using the
- Handling Client Connections:
- When a client connects, an event handler logs the connection and assigns a
WebSocket
object (referred to assocket
) to the client. - This socket object is used to facilitate communication between the server and the connected client.
- When a client connects, an event handler logs the connection and assigns a
server.on('connection', (socket) => {
console.log('A client connected.');
});
- Receiving and Broadcasting Messages:
- The server listens for incoming messages from the connected client via the
message
event on thesocket
object. - When a message is received, it is broadcasted to all connected clients except the sender to prevent duplicate messages.
- The server listens for incoming messages from the connected client via the
socket.on('message', (message) => {
server.clients.forEach((client) => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
- Handling Disconnections:
- When a client disconnects, the
close
event is triggered, and the server logs the disconnection.
- When a client disconnects, the
socket.on('close', () => {
console.log('A client disconnected.');
});
2. WebSocket Client (client/js/app.js
)
The client is responsible for establishing a WebSocket connection with the server and sending/receiving messages.
- Establishing a WebSocket Connection:
- A connection to the WebSocket server is created using the
WebSocket
API. - The URL
ws://localhost:8080
points to the WebSocket server running locally.
- A connection to the WebSocket server is created using the
const socket = new WebSocket('ws://localhost:8080');
- Listening for Incoming Messages:
- The
onmessage
event on thesocket
object listens for messages sent by the server. - Each message is logged to the browser console for testing or further UI updates.
- The
socket.onmessage = (event) => {
console.log(`Message from server: ${event.data}`);
};
- Sending Messages to the Server:
- The client provides a simple input form to capture user messages.
- When the "Send" button is clicked, the message in the input field is sent to the server.
document.getElementById('sendBtn').addEventListener('click', () => {
const input = document.getElementById('messageInput').value;
socket.send(input);
});
3. HTML Structure (client/index.html
)
The HTML structure serves as the UI for the WebSocket client.
- Input Field and Button:
- The input field (
<input>
) allows users to type messages. - The button (
<button>
) triggers the JavaScript logic to send the message to the server.
- The input field (
<input type="text" id="messageInput" placeholder="Type a message">
<button id="sendBtn">Send</button>
- JavaScript Integration:
- The
<script>
tag includes the JavaScript file (app.js
) responsible for WebSocket logic.
- The
<script src="./js/app.js"></script>
- Example in Action:
- When a user types "Hello, World!" in the input field and clicks "Send," the message is transmitted to the server.
- The server broadcasts the message to other connected clients.
- Each client, upon receiving the message, logs it to the console or displays it in the UI.
Conclusion
WebSockets offer a powerful way to build real-time applications by maintaining an open connection between the server and the client. By following this guide, you’ve learned how to:
- Set up a WebSocket server and client.
- Handle bi-directional communication.
- Broadcast messages dynamically.
Start building your real-time projects today and explore the endless possibilities WebSockets provide!