Node.js — WebSockets
What are WebSockets?
WebSockets provide full-duplex communication over a single TCP connection.
Basic WebSocket Server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (data) => {
console.log('Received:', data);
ws.send(`Echo: ${data}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
WebSocket Client
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', () => {
ws.send('Hello Server!');
});
ws.on('message', (data) => {
console.log('Received:', data);
});
Broadcasting
wss.on('connection', (ws) => {
ws.on('message', (data) => {
// Broadcast to all clients
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
});
});
With Express
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
// Handle connection
});
server.listen(3000);
Mini Practice
- Create a WebSocket server
- Send and receive messages
- Broadcast to all clients
- Integrate with Express
Up Next
Continue with Database — connecting to databases.
Related Topics
Frequently Asked Questions about WebSockets
What is WebSockets in Node.js?
WebSockets is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn WebSockets?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn WebSockets.
Why is WebSockets important in Node.js?
WebSockets is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.