logo
eng-flag

WebSocket Cheatsheet

Table of Contents

  1. Introduction to WebSockets
  2. WebSocket Handshake
  3. WebSocket Protocol
  4. WebSocket API
  5. Server-Side Implementation
  6. Client-Side Implementation
  7. WebSocket Events
  8. WebSocket Methods
  9. WebSocket States
  10. Error Handling
  11. Security Considerations
  12. Scaling WebSockets
  13. Best Practices
  14. Tools and Libraries

Introduction to WebSockets

WebSocket is a protocol that enables full-duplex, bidirectional communication between a client and a server over a single TCP connection. It's designed for real-time, event-driven applications such as chat systems, live updates, and gaming.

WebSocket Handshake

The WebSocket connection starts with an HTTP upgrade request:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

Server response:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

WebSocket Protocol

  • Uses ws:// or wss:// (for secure WebSocket) URL scheme
  • Supports text and binary data frames
  • Includes a ping/pong mechanism for keeping connections alive

WebSocket API

The WebSocket API provides a simple interface for creating and managing WebSocket connections.

const socket = new WebSocket('ws://example.com/socketserver');

Server-Side Implementation

Example using Node.js and the ws library:

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

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('Welcome to the WebSocket server!');
});

Client-Side Implementation

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

socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

socket.addEventListener('message', function (event) {
    console.log('Message from server:', event.data);
});

WebSocket Events

  1. open: Fired when the connection is established
  2. message: Fired when data is received
  3. error: Fired when an error occurs
  4. close: Fired when the connection is closed
socket.addEventListener('open', (event) => {
    console.log('WebSocket connection opened');
});

socket.addEventListener('message', (event) => {
    console.log('Received message:', event.data);
});

socket.addEventListener('error', (event) => {
    console.error('WebSocket error:', event);
});

socket.addEventListener('close', (event) => {
    console.log('WebSocket connection closed');
});

WebSocket Methods

  1. send(): Sends data through the WebSocket connection
  2. close(): Closes the WebSocket connection
// Sending data
socket.send('Hello, server!');

// Closing the connection
socket.close();

WebSocket States

The readyState property indicates the state of the WebSocket connection:

  • WebSocket.CONNECTING (0): The connection is not yet open
  • WebSocket.OPEN (1): The connection is open and ready to communicate
  • WebSocket.CLOSING (2): The connection is in the process of closing
  • WebSocket.CLOSED (3): The connection is closed or couldn't be opened
if (socket.readyState === WebSocket.OPEN) {
    socket.send('Data');
}

Error Handling

socket.addEventListener('error', (error) => {
    console.error('WebSocket Error:', error);
});

// Handling specific errors
socket.addEventListener('close', (event) => {
    if (event.code === 1006) {
        console.error('Connection closed abnormally');
    }
});

Security Considerations

  1. Use WSS (WebSocket Secure) for encrypted connections
  2. Validate and sanitize all incoming messages
  3. Implement proper authentication and authorization
  4. Protect against cross-site WebSocket hijacking (CSWSH)
  5. Set appropriate timeouts and implement reconnection strategies
const socket = new WebSocket('wss://secure.example.com');

Scaling WebSockets

  1. Use a load balancer with WebSocket support
  2. Implement a pub/sub system (e.g., Redis) for distributing messages across multiple server instances
  3. Consider using WebSocket clustering solutions
  4. Optimize message size and frequency
  5. Implement proper connection management and cleanup

Best Practices

  1. Use a heartbeat mechanism to keep connections alive
  2. Implement reconnection logic on the client side
  3. Handle connection errors and timeouts gracefully
  4. Use binary data for large payloads or when performance is critical
  5. Implement proper error handling and logging
  6. Use sub-protocols to define specific communication patterns
  7. Optimize for mobile devices (consider battery life and data usage)
  8. Implement rate limiting to prevent abuse
  9. Use compression for large text payloads
  10. Properly close WebSocket connections when they're no longer needed

Example heartbeat implementation:

// Client-side
function heartbeat() {
    if (socket.readyState === WebSocket.OPEN) {
        socket.send('__ping__');
        setTimeout(heartbeat, 30000);
    }
}

socket.addEventListener('open', heartbeat);

socket.addEventListener('message', (event) => {
    if (event.data === '__pong__') {
        console.log('Received pong');
    } else {
        console.log('Received:', event.data);
    }
});

// Server-side
wss.on('connection', (ws) => {
    ws.isAlive = true;
    ws.on('pong', () => {
        ws.isAlive = true;
    });
    ws.on('message', (message) => {
        if (message === '__ping__') {
            ws.send('__pong__');
        }
    });
});

setInterval(() => {
    wss.clients.forEach((ws) => {
        if (!ws.isAlive) return ws.terminate();
        ws.isAlive = false;
        ws.ping();
    });
}, 30000);

Tools and Libraries

  1. Socket.IO: Provides real-time bidirectional event-based communication
  2. ws: A simple WebSocket client and server implementation for Node.js
  3. WebSocket-Node: A WebSocket client and server implementation in Node.js
  4. SockJS: Provides a WebSocket-like object for JavaScript
  5. Pusher: Hosted WebSocket infrastructure
  6. SignalR: Real-time ASP.NET library (supports WebSockets)
  7. websockets: WebSocket client and server library for Python
  8. Gorilla WebSocket: WebSocket implementation for Go
  9. Faye: Simple pub/sub messaging for web and Node.js applications
  10. µWebSockets: Highly scalable WebSocket server and client implementation in C++

2024 © All rights reserved - buraxta.com