WebSocket Server

Optimized Digital Twin Server

Industrial WebSocket Server

High-Performance Digital Twin Server

An optimized WebSocket server designed for industrial automation and digital twin applications. Features subscription-based messaging, real-time telemetry, and scalable client management.

High Frequency
50Hz joint states, optimized message queuing
Multi-Client
Scalable client management with per-client subscriptions
Real-time Monitoring
Performance stats, throughput, and bandwidth tracking
Topic-based
MQTT-style topic subscriptions with wildcards
Technical Specifications

Performance

Joint States Frequency50Hz
State Updates1Hz
Message Queue Processing60Hz

Data Topics

• robots/arm1/joint_states@v1
• robots/arm1/state@v1
• robots/arm1/plan@v1
• robots/arm1/annotations@v1

Commands

• subscribe / unsubscribe
• ping / pong
• command execution
• emergency_stop
Server Implementation
Complete WebSocket server implementation with optimized performance features
// ws-server-optimized.js
import { WebSocketServer } from "ws";
import { performance } from "perf_hooks";

class DigitalTwinServer {
  constructor(port = 8765) {
    this.port = port;
    this.wss = null;
    this.clients = new Set();
    this.subscriptions = new Map(); // client -> topics
    this.telemetryIntervals = new Map(); // client -> intervals
    this.messageQueue = new Map(); // client -> queue
    this.stats = {
      messagesSent: 0,
      bytesTransmitted: 0,
      connections: 0,
      startTime: Date.now()
    };
  }

  start() {
    this.wss = new WebSocketServer({ port: this.port });
    console.log(`[Server] Digital Twin WS Server listening on :${this.port}`);

    this.wss.on("connection", (ws, req) => {
      this.handleConnection(ws, req);
    });

    // Start performance monitoring
    this.startMonitoring();
  }

  handleConnection(ws, req) {
    const clientId = `${req.socket.remoteAddress}-${Date.now()}`;
    console.log(`[Server] Client connected: ${clientId}`);

    // Initialize client
    this.clients.add(ws);
    this.subscriptions.set(ws, new Set());
    this.messageQueue.set(ws, []);
    this.stats.connections++;

    // Setup client handlers
    ws.on("message", (message) => {
      this.handleMessage(ws, message);
    });

    ws.on("close", () => {
      this.handleDisconnection(ws, clientId);
    });

    ws.on("error", (error) => {
      console.error(`[Server] Client error ${clientId}:`, error);
    });

    // Send initial state
    this.sendMessage(ws, {
      topic: "system/connected",
      data: {
        timestamp: Date.now(),
        clientId,
        serverVersion: "1.0.0"
      }
    });

    // Start telemetry for this client
    this.startTelemetry(ws);
  }

  handleMessage(ws, message) {
    try {
      const msg = JSON.parse(message.toString());

      switch (msg.cmd) {
        case "subscribe":
          this.handleSubscribe(ws, msg.topics || []);
          break;
        case "unsubscribe":
          this.handleUnsubscribe(ws, msg.topics || []);
          break;
        case "ping":
          this.sendMessage(ws, { topic: "system/pong", data: { timestamp: Date.now() } });
          break;
        case "command":
          this.handleCommand(ws, msg);
          break;
        default:
          console.log(`[Server] Unknown command: ${msg.cmd}`);
      }
    } catch (error) {
      console.error("[Server] Failed to parse message:", error);
    }
  }

  startTelemetry(ws) {
    const intervals = [];

    // Joint states at 50Hz (20ms)
    intervals.push(setInterval(() => {
      if (this.shouldSend(ws, "robots/arm1/joint_states@v1")) {
        this.queueMessage(ws, {
          topic: "robots/arm1/joint_states@v1",
          data: {
            joints: this.generateJointStates(),
            timestamp: Date.now(),
            velocity: this.generateJointVelocities(),
            effort: this.generateJointEfforts()
          }
        });
      }
    }, 20));

    // State updates at 1Hz
    intervals.push(setInterval(() => {
      if (this.shouldSend(ws, "robots/arm1/state@v1")) {
        this.queueMessage(ws, {
          topic: "robots/arm1/state@v1",
          data: {
            state: this.getCurrentState(),
            taskId: `task-${Math.floor(Date.now() / 10000)}`,
            progress: Math.random(),
            timestamp: Date.now()
          }
        });
      }
    }, 1000));

    this.telemetryIntervals.set(ws, intervals);
  }

  // Data generators and other methods...
}

// Usage
const server = new DigitalTwinServer(8765);
server.start();

// Export for use as module
export default DigitalTwinServer;
Interactive Demo
Experience the WebSocket server functionality with real-time telemetry and professional robot control interface
Robot: R01_Robot_LOBFeedrate: 0
Active Path Rel:x1
Mode: Manual Reduced SpeedStatus: Robot OFF
Virtual
Faulted
Ready
Available
Energized
Transform Enabled
Stopping
Stopped
Standstill
Path Following Active
Singularity
Safety Enabled
IOs Zone Out...
Load Protection
Tracking
KUKA KR 6 R900
Main Joints (J1-J3)
Wrist Joints (J4-J6)
Links & Structure
Motion Path
Safety Zone
Power Grasp
Precision Grasp
Reach: 901mm | Payload: 6kg

Arm Configuration: Righty Below / no Flip

Linear Speed: 0.00 mm/s
Linear Acceleration: 0.00 mm/s²
Angular Speed: 0.00 deg/s
Angular Acceleration: 0.00 deg/s²

Event Message

16:37:58.809444Safety Torque Off
16:37:58.809434Safety Torque Off
16:37:58.809424Safety Torque Off
16:37:58.809414Safety Torque Off
16:37:58.809404Safety Torque Off
16:37:58.809394Torque allowed
16:37:58.803610Handkit - Available
16:37:58.803389System Ready

Event Time Stamp

16:37:58.809444
16:37:58.809434
16:37:58.809424
16:37:58.809414

Joint Positions

J10.00 deg
X: 17.75 mm
Y: 6.29 mm
Z: 1063.70 mm
Rx: 0.00 deg
Ry: 0.00 deg
Rz: 153.15 deg
J20.00 deg
X: 67.58 mm
Y: 19.41 mm
Z: 1063.32 mm
Rx: 0.00 deg
Ry: 0.00 deg
Rz: 128.83 deg
J30.00 deg
X: 30.11 mm
Y: 57.71 mm
Z: 1022.08 mm
Rx: 0.00 deg
Ry: 0.00 deg
Rz: 274.34 deg
J40.00 deg
X: 79.49 mm
Y: 18.83 mm
Z: 1055.53 mm
Rx: 0.00 deg
Ry: 0.00 deg
Rz: 306.47 deg
J50.00 deg
X: 2.66 mm
Y: 89.80 mm
Z: 1052.83 mm
Rx: 0.00 deg
Ry: 0.00 deg
Rz: 192.76 deg
J60.00 deg
X: 76.40 mm
Y: 50.86 mm
Z: 1032.40 mm
Rx: 0.00 deg
Ry: 0.00 deg
Rz: 86.42 deg
Linear Speed0.00 mm/s
Linear Acceleration0.00 mm/s²
Angular Speed0.00 deg/s
Angular Acceleration0.00 deg/s²
Usage Instructions
How to run and connect to the WebSocket server

1. Start the Server

node ws-server-optimized.js

2. Connect Client

const ws = new WebSocket('ws://localhost:8765');

3. Subscribe to Topics

ws.send(JSON.stringify({ cmd: "subscribe", topics: ["robots/arm1/#"] }));

4. Send Commands

ws.send(JSON.stringify({ cmd: "command", data: { action: "emergency_stop" } }));