WebSocket Communication in Node.js With Native ws
Library
WebSockets enable real-time, two-way communication between clients and servers over a single TCP connection. They’re perfect for building chat apps, live notifications, collaborative tools, and more. In this guide, we’ll walk through implementing a basic WebSocket server and client using Node.js and the ws
library.
Step 1: Install the ws
Library
npm install ws
Step 2: Create a WebSocket Server
// server.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', socket => {
console.log('Client connected');
socket.on('message', message => {
console.log(`Received: ${message}`);
// Echo the message back
socket.send(`Server says: ${message}`);
});
socket.on('close', () => {
console.log('Client disconnected');
});
});
This sets up a WebSocket server on port 8080
. When a client connects, it can send and receive messages in real time.
Step 3: Create a WebSocket Client (Browser)
<script>
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connected to WebSocket server');
socket.send('Hello from client!');
});
socket.addEventListener('message', event => {
console.log('Message from server:', event.data);
});
socket.addEventListener('close', () => {
console.log('Connection closed');
});
</script>
Step 4: Broadcast Messages to All Clients
server.on('connection', socket => {
socket.on('message', message => {
// Broadcast to all connected clients
server.clients.forEach(client => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(`Broadcast: ${message}`);
}
});
});
});
Security Note
For production use, always secure your WebSocket connection using WSS (WebSocket over HTTPS), and validate or sanitize all messages to avoid injection attacks.
Conclusion
The ws
library offers a powerful and minimal API for real-time communication in Node.js. It’s lightweight, fast, and production-ready for many use cases, from live dashboards to collaborative tools and gaming backends.
If this post helped you, consider supporting me: buymeacoffee.com/hexshift
Top comments (0)