← Back to Chapters

WebSocket API Testing

? WebSocket API Testing

? Quick Overview

WebSocket is a protocol that enables full-duplex, real-time communication between a client and a server over a single persistent connection. Unlike traditional HTTP request-response models, WebSockets allow data to be pushed instantly from server to client. This makes WebSockets ideal for chat applications, live notifications, real-time dashboards, and multiplayer games.

? Key Concepts

  • Persistent connection between client and server
  • Bi-directional data flow
  • Low latency communication
  • Event-driven messaging
  • Stateful connection lifecycle

? Syntax / Theory

A WebSocket connection starts as an HTTP handshake and then upgrades to the WebSocket protocol. Once connected, both client and server can send messages independently. WebSocket URLs use ws:// or wss:// (secure).

? View Code Example
// Creating a new WebSocket connection
const socket = new WebSocket("wss://echo.websocket.org");

// Event triggered when connection opens
socket.onopen = () => {
socket.send("Hello WebSocket");
};

// Event triggered when message is received
socket.onmessage = (event) => {
console.log(event.data);
};

// Event triggered when connection closes
socket.onclose = () => {
console.log("Connection closed");
};

? Live Output / Explanation

When the connection opens, the client sends a message to the server. The server echoes the message back, which is then logged in the console. The connection remains open until explicitly closed.

? Interactive Example / Visual Flow

 
Disconnected
> Click 'Connect' to start a WebSocket session...

Client ➜ WebSocket Handshake ➜ Persistent Connection ➜ Real-Time Messages ➜ Client

This flow demonstrates how data travels instantly without repeated HTTP requests.

? Use Cases

  • Real-time chat applications
  • Live sports score updates
  • Stock market tickers
  • Online multiplayer games
  • Collaborative editing tools

✅ Tips & Best Practices

  • Always handle connection errors gracefully
  • Use secure WebSockets (wss) in production
  • Close unused connections to save resources
  • Validate all incoming messages

? Try It Yourself

  1. Create a simple WebSocket client in the browser
  2. Send messages from client to server
  3. Log received messages in real time
  4. Test WebSocket APIs using Postman