Did you know? All Video & Audio API plans include a $100 free usage credit each month so you can build and test risk-free. View Plans ->

WebRTC For The Brave

Real-time Communication with WebSockets

What are WebSockets?

WebSockets provide a persistent connection between a client and server that both parties can use to send data at any time. Unlike HTTP, which follows a request-response pattern, WebSockets allow for real-time, two-way communication.

Imagine HTTP as sending letters through the mail—you send a request and wait for a response. WebSockets, on the other hand, are like having a phone conversation where both parties can speak whenever they need to.

Why Do We Need WebSockets?

Before WebSockets, developers used workarounds like long polling to simulate real-time communication. These approaches had significant limitations:

  • They required constant new HTTP connections
  • They added latency to communication
  • They consumed unnecessary bandwidth
  • They complicated server implementation

WebSockets solve these problems by establishing a single, persistent connection that remains open until explicitly closed by either the client or server.

How WebSockets Work

WebSockets begin with a standard HTTP request that includes special headers asking to "upgrade" the connection. If the server supports WebSockets, it responds with an agreement to the upgrade. At this point, the HTTP connection is replaced by a WebSocket connection using the same underlying TCP/IP connection.

The WebSocket protocol uses two URI schemes:

  • ws:// for unencrypted connections (similar to HTTP)
  • wss:// for encrypted connections (similar to HTTPS)

The WebSocket Handshake

The WebSocket handshake starts with an HTTP request like this:

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

If the server accepts, it responds:

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

This completes the handshake, and the connection is now upgraded to a WebSocket.

WebSocket Communication

Once established, both client and server can send messages to each other at any time. These messages are transmitted as "frames" - packets of data that can be sent independently.

WebSocket messages can contain:

  • Text data (UTF-8)
  • Binary data
  • Control frames (for managing the connection)

WebSockets maintain a persistent connection using a system of "ping" and "pong" frames to check if the other end is still responsive.

Using WebSockets in JavaScript

The WebSocket API is surprisingly simple to use:

javascript
            // Create a new WebSocket connection
const socket = new WebSocket('wss://example.com/socket');

// Connection opened
socket.addEventListener('open', (event) => {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', (event) => {
    console.log('Message from server:', event.data);
});

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

// Connection closed
socket.addEventListener('close', (event) => {
    console.log('Connection closed. Code:', event.code, 'Reason:', event.reason);
});

// To send a message
function sendMessage(message) {
    socket.send(message);
}

// To close the connection
function closeConnection() {
    socket.close();
}
        

WebSocket Use Cases

WebSockets excel in applications requiring real-time updates or low-latency communication:

  • Chat applications: Messages appear instantly without refreshing
  • Live sports updates: Scores and plays update in real-time
  • Collaborative editing tools: Multiple users can see changes as they happen
  • Financial trading platforms: Stock prices update in milliseconds
  • Gaming: Real-time player movements and actions
  • IoT devices: Continuous data streaming from sensors

WebSockets vs. HTTP

While both protocols use TCP/IP connections, they serve different purposes:

Feature HTTP WebSockets
Connection New connection per request Persistent connection
Communication Unidirectional Bidirectional
Overhead Headers sent with each request Minimal overhead after handshake
State Stateless Stateful
Use case Request-response interactions Real-time data exchange

Connection Interruptions

Network disruptions can break WebSocket connections. You can implement automatic reconnection logic to solve this:

javascript
            function createWebSocket() {
    const socket = new WebSocket('wss://example.com/socket');

    socket.addEventListener('close', (event) => {
        if (!event.wasClean) {
            console.log('Connection lost. Reconnecting...');
            setTimeout(createWebSocket, 5000); // Try to reconnect after 5 seconds
        }
    });

    return socket;
}
        

Security Considerations

WebSockets face unique security challenges:

  • Use wss:// (secure WebSockets) to encrypt data
  • Validate all messages to prevent injection attacks
  • Implement authentication for connection establishment
  • Set up proper CORS restrictions for the WebSocket endpoint
  • Consider rate limiting to prevent abuse