Home  Tech   Real life e ...

Real-life examples where WebSocket is used

Here are three real-life examples where WebSocket or socket-based communication is commonly used, along with Node.js code snippets demonstrating their implementation:

1. Real-Time Chat Application

Use Case: A real-time chat application where users can send and receive messages instantly.

Node.js Implementation:

const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();

// Serve static files (optional)
app.use(express.static('public'));

// Create HTTP server
const server = http.createServer(app);

// Initialize WebSocket server
const wss = new WebSocket.Server({ server });

// WebSocket server event listeners
wss.on('connection', (ws) => {
  console.log('A new client connected');

  // Message received from a client
  ws.on('message', (message) => {
    console.log('Received:', message);
    
    // Broadcast message to all clients
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });

  // Client disconnects
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

// Start server
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
  console.log(`WebSocket server running on ws://localhost:${PORT}`);
});

Example Usage:

2. Real-Time Collaboration Tool

Use Case: A collaborative tool where multiple users can simultaneously edit documents or work together on a project in real-time.

Node.js Implementation:

const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();

// Serve static files (optional)
app.use(express.static('public'));

// Create HTTP server
const server = http.createServer(app);

// Initialize WebSocket server
const wss = new WebSocket.Server({ server });

// In-memory storage for shared document
let sharedDocument = '';

// WebSocket server event listeners
wss.on('connection', (ws) => {
  console.log('A new client connected');

  // Send current shared document to new client
  ws.send(sharedDocument);

  // Message received from a client
  ws.on('message', (message) => {
    console.log('Received:', message);
    
    // Update shared document
    sharedDocument = message;

    // Broadcast updated document to all clients
    wss.clients.forEach((client) => {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(sharedDocument);
      }
    });
  });

  // Client disconnects
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

// Start server
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
  console.log(`WebSocket server running on ws://localhost:${PORT}`);
});

Example Usage:

3. Real-Time Dashboard or Monitoring System

Use Case: A real-time dashboard or monitoring system that displays live data updates from various sources.

Node.js Implementation:

const WebSocket = require('ws');
const http = require('http');
const express = require('express');
const app = express();

// Serve static files (optional)
app.use(express.static('public'));

// Create HTTP server
const server = http.createServer(app);

// Initialize WebSocket server
const wss = new WebSocket.Server({ server });

// Simulated data generator (example)
function generateData() {
  return {
    timestamp: new Date().toLocaleTimeString(),
    value: Math.random() * 100
  };
}

// WebSocket server event listeners
wss.on('connection', (ws) => {
  console.log('A new client connected');

  // Send simulated data updates at regular intervals
  const intervalId = setInterval(() => {
    const data = generateData();
    ws.send(JSON.stringify(data));
  }, 1000);

  // Stop sending data when client disconnects
  ws.on('close', () => {
    console.log('Client disconnected');
    clearInterval(intervalId);
  });
});

// Start server
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => {
  console.log(`WebSocket server running on ws://localhost:${PORT}`);
});

Example Usage:

Published on: Jun 14, 2024, 12:37 AM  
 

Comments

Add your comment