WebSockets provide a two way communication between a client and server over a persistent TCP connection. Unlike traditional HTTP request-response patters, WebSockets allow real-time data exchange where either party can send messages at any time

WebSocket can only transmit text or binary data over the network. When we want to send JavaScript objects, we need to convert them to a string format first. This is where JSON.stringify() and JSON.parse() come i

In WebSocket communication, there are several common event string types used to handle different aspects of the WebSocket connection lifecycle and data transfer

WebSocket Client Events

// Connection events
websocket.onopen = (event) => {
    // Handle connection opened
};

websocket.onclose = (event) => {
    // Handle connection closed
    // event.code - closure code
    // event.reason - reason for closure
    // event.wasClean - whether closure was clean
};

websocket.onerror = (event) => {
    // Handle errors
};

websocket.onmessage = (event) => {
    // Handle incoming messages
    // event.data contains the message
};

WebSocket Server Events

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
    // New client connected

    ws.on('message', (data) => {
        // Handle incoming messages
    });

    ws.on('close', () => {
        // Handle client disconnection
    });

    ws.on('error', (error) => {
        // Handle errors
    });
});

Custom Event Types

// Subscription events
{
    "event": "subscribe",
    "channel": "trading",
    "symbol": "BTC/USD"
}

// Unsubscribe events
{
    "event": "unsubscribe",
    "channel": "trading",
    "symbol": "BTC/USD"
}

// Data events
{
    "event": "data",
    "channel": "trading",
    "data": {...}
}

// Error events
{
    "event": "error",
    "message": "Invalid subscription parameters"
}

// Heartbeat/ping events
{
    "event": "ping",
    "timestamp": 1234567890
}

// Authentication events
{
    "event": "auth",
    "token": "your_auth_token"
}

WebSocket Channels

WebSocket Channels (topics/rooms in some implementations) are a way to organize and segregate WebSocket communications into logical groups. Think of them like different radio frequencies or TV Channels. Clients can “tune in” to specific channels to receive