WebSocket Implementation
Learn to implement WebSockets for real-time bidirectional communication
60 minā¢By Priygop Teamā¢Last updated: Feb 2026
What are WebSockets?
WebSockets provide a persistent connection between a client and server, allowing real-time bidirectional communication. Unlike HTTP requests, WebSockets maintain an open connection for instant data exchange.
Basic WebSocket Server
Example
// Install ws library
npm install ws
// Basic WebSocket server
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
console.log('New client connected');
// Send welcome message
ws.send(JSON.stringify({
type: 'welcome',
message: 'Welcome to the WebSocket server!'
}));
// Handle incoming messages
ws.on('message', function incoming(message) {
try {
const data = JSON.parse(message);
console.log('Received:', data);
// Echo the message back
ws.send(JSON.stringify({
type: 'echo',
message: data.message,
timestamp: new Date().toISOString()
}));
} catch (error) {
ws.send(JSON.stringify({
type: 'error',
message: 'Invalid JSON format'
}));
}
});
// Handle client disconnect
ws.on('close', function close() {
console.log('Client disconnected');
});
// Handle errors
ws.on('error', function error(err) {
console.error('WebSocket error:', err);
});
});
console.log('WebSocket server running on port 8080');WebSocket Client Implementation
Example
// WebSocket client (browser)
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = function(event) {
console.log('Connected to WebSocket server');
// Send a message
ws.send(JSON.stringify({
type: 'chat',
message: 'Hello from client!'
}));
};
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received:', data);
if (data.type === 'welcome') {
console.log('Server says:', data.message);
} else if (data.type === 'echo') {
console.log('Echo:', data.message);
}
};
ws.onclose = function(event) {
console.log('Disconnected from server');
};
ws.onerror = function(error) {
console.error('WebSocket error:', error);
};
// Send message function
function sendMessage(message) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: 'chat',
message: message
}));
}
}