Working with WebSocket using Nodejs
keshav Sandhu
Posted on October 11, 2024
WebSockets provide a full-duplex, bidirectional communication channel over a single TCP connection, allowing real-time data exchange between clients and servers. They are commonly used in applications requiring low-latency, interactive communication, such as chat applications, online gaming, live notifications, and financial trading platforms.
In Node.js, WebSockets can be implemented using libraries such as ws
or Socket.IO
. While WebSockets handle real-time communication over a persistent connection, Socket.IO offers a richer set of functionalities like reconnection and broadcasting.
Key Concepts in WebSockets
- Persistent Connection: Once established, the WebSocket connection remains open, unlike traditional HTTP where a request-response is used for every communication.
- Full-Duplex Communication: Data can be sent and received simultaneously between the client and server.
- Low Overhead: Since there’s no constant opening/closing of connections, WebSockets are more efficient for real-time applications.
-
Event-Based Model: WebSockets operate using an event-based model where you can listen for events like
message
,open
,close
, anderror
.
Installing WebSocket Library in Node.js
You can use the ws
library, which is a popular choice for WebSocket implementations in Node.js.
npm install ws
WebSocket Functions Using ws
1. Creating a WebSocket Server
const WebSocket = require('ws');
// Create a WebSocket server on port 8080
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', ws => {
console.log('New client connected');
// Listening for messages from the client
ws.on('message', message => {
console.log(`Received: ${message}`);
// Echo the message back to the client
ws.send(`Server: ${message}`);
});
// Handling client disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
// Sending a message to the client on connection
ws.send('Welcome to the WebSocket server!');
});
2. Client-Side WebSocket Connection
In your client-side JavaScript (for example, inside an HTML file):
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', (event) => {
console.log('Connected to server');
socket.send('Hello Server!');
});
socket.addEventListener('message', (event) => {
console.log('Message from server: ', event.data);
});
socket.addEventListener('close', (event) => {
console.log('Connection closed');
});
</script>
3. Key WebSocket Functions
-
WebSocket Server Methods:
-
ws.on('connection', callback)
: Listens for new client connections. -
ws.on('message', callback)
: Listens for incoming messages from a client. -
ws.on('close', callback)
: Fires when a client disconnects. -
ws.send(message)
: Sends a message to the connected client.
-
-
WebSocket Client Methods:
-
ws.send(data)
: Sends data to the server. -
ws.on('open', callback)
: Fires when the connection to the server is established. -
ws.on('message', callback)
: Fires when a message is received from the server. -
ws.on('close', callback)
: Fires when the connection to the server is closed.
-
Common Use Cases of WebSockets
1. Chat Applications
Real-time chat applications require immediate communication between users. WebSockets allow sending and receiving chat messages in real-time without constantly polling the server.
2. Online Gaming
Multiplayer online games require fast and low-latency communication to ensure players have a smooth, interactive experience. WebSockets are used for sending in-game events, such as player movement and actions, between clients and the server.
3. Real-Time Notifications
WebSockets can be used to deliver real-time updates to users, such as notifications in social media apps, or updates in collaborative tools (e.g., Google Docs-style real-time editing).
4. Live Tracking
WebSockets are useful for applications like live location tracking (Uber, delivery apps) where users see real-time updates of a moving vehicle on a map.
5. Stock Price Tickers
For financial trading platforms or cryptocurrency exchanges, WebSockets enable real-time price updates for stocks, currencies, or other assets.
Simple WebSocket Project: Real-Time Chat Application
Project Structure:
|-- index.js (server)
|-- public
|-- index.html (client)
1. Server-Side (Node.js + WebSocket): index.js
const WebSocket = require('ws');
const http = require('http');
const fs = require('fs');
// Create HTTP server to serve the client
const server = http.createServer((req, res) => {
fs.readFile('./public/index.html', (err, data) => {
if (err) {
res.writeHead(500);
return res.end('Error loading file');
}
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
});
});
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
console.log('New client connected');
// Broadcast message to all connected clients
ws.on('message', message => {
console.log(`Received: ${message}`);
wss.clients.forEach(client => {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`Client says: ${message}`);
}
});
});
// Send a welcome message
ws.send('Welcome to the chat!');
});
server.listen(8080, () => {
console.log('Server is listening on port 8080');
});
2. Client-Side (HTML + JavaScript): public/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>Real-Time Chat</h1>
<input type="text" id="message" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = new WebSocket('ws://localhost:8080');
// Listen for messages from the server
socket.addEventListener('message', (event) => {
const messageList = document.getElementById('messages');
const newMessage = document.createElement('li');
newMessage.textContent = event.data;
messageList.appendChild(newMessage);
});
function sendMessage() {
const messageInput = document.getElementById('message');
const message = messageInput.value;
socket.send(message);
messageInput.value = '';
}
</script>
</body>
</html>
3. Running the Project
- Start the WebSocket server by running
node index.js
. - Open
localhost:8080
in a browser, and you'll be able to send and receive real-time messages using WebSockets.
Advanced Features with WebSockets
- Authentication: Use authentication tokens or cookies to ensure only authorized users can establish WebSocket connections.
-
Broadcasting: In multi-client scenarios, messages sent by one client can be broadcast to all other clients using the
ws.clients
set. - Reconnection: To handle disconnections, you can implement logic to automatically reconnect the WebSocket if the connection is lost (handled better with Socket.IO).
- Compression: Use WebSocket extensions such as permessage-deflate to compress data over the WebSocket, especially useful in low-bandwidth situations.
Conclusion
WebSockets in Node.js provide a powerful way to create real-time, low-latency communication channels. With libraries like ws
and Socket.IO
, it's easy to build scalable applications like chat platforms, live notification systems, and real-time data feeds. Understanding the core functions and use cases helps you apply WebSockets in the right situations, especially for interactive or real-time applications.
Posted on October 11, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.