Before you begin, make sure that Node.js and npm are installed on your system. If not, download and install Node.js from the official website.
Verify the installation:
node -v
npm -v
Create a new Node.js project:
mkdir websocket-project
cd websocket-project
npm init -y
Install necessary dependencies: WebSockets in Node.js can be easily implemented using the ws
library.
npm install ws express
To implement WebSockets, we will first create a simple WebSocket server using the ws
package.
Create a WebSocket server: In your project directory, create a file called server.js
and add the following code:
const express = require('express');
const WebSocket = require('ws');
const app = express();
const server = app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
// Create a WebSocket server on top of the HTTP server
const wss = new WebSocket.Server({ server });
// Handle incoming WebSocket connections
wss.on('connection', (ws) => {
console.log('A new client connected');
// Send a welcome message to the client
ws.send('Welcome to the WebSocket server!');
// Broadcast received messages to all clients
ws.on('message', (message) => {
console.log(`Received message: ${message}`);
wss.clients.forEach((client) => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
// Handle client disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
});
Explanation:
ws
package to create a WebSocket server.Now that the WebSocket server is running, we need to create a simple client-side application to connect to the server and exchange messages.
Create an HTML file: In the same project directory, create an index.html
file and add the following code:7
<!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</h1>
<div id="messages"></div>
<input type="text" id="message" placeholder="Type a message..." />
<button onclick="sendMessage()">Send</button>
<script>
const ws = new WebSocket('ws://localhost:3000');
const messagesDiv = document.getElementById('messages');
const messageInput = document.getElementById('message');
// Display incoming messages
ws.onmessage = (event) => {
const message = document.createElement('p');
message.textContent = event.data;
messagesDiv.appendChild(message);
};
// Send a message to the server
function sendMessage() {
const message = messageInput.value;
if (message) {
ws.send(message);
messageInput.value = '';
}
}
</script>
</body>
</html>
Explanation:
ws://localhost:3000
.div
with the ID messages
.Now, you can run both the server and the client to see WebSockets in action.
Start the WebSocket server:
Open the client in a browser: Open the index.html
file in a web browser. You should see the WebSocket chat interface.
Test the functionality:
index.html
file.WebSockets in Node.js provide an efficient and scalable way to implement real-time communication in your applications. This method is ideal for applications that require low-latency communication, such as chat applications, online gaming, live notifications, and more. By using WebSockets, you can establish a persistent connection between the client and server, enabling data to flow in both directions seamlessly.
In this guide, we set up a basic WebSocket server using Node.js and the ws
library and demonstrated how to create a simple client-side application for real-time messaging. With this foundation, you can easily extend this functionality to build more complex, real-time features in your web applications.
Pros:
Cons: