⚡ Full-Duplex, Low-Latency Communication Beyond Request-Response
While REST and GraphQL operate primarily on stateless, request-response lifecycles over standard HTTP, modern real-time systems—such as live trading engines, financial notifications, collaborative documents, IoT telemetry, and interactive chat architectures—require persistent, bi-directional channels. The WebSocket Protocol (RFC 6455) solves the overhead of continuous HTTP polling by initiating an HTTP 101 Switching Protocols handshake over a single TCP connection, establishing a permanent full-duplex conduit. Unlike HTTP where the client always initiates conversations, WebSockets allow servers to push asynchronous messages down to clients instantly. In test automation, verifying WebSockets requires handling binary and text framing, maintaining heartbeat health checks via Ping/Pong opcodes, tracking message sequencing, and validating application-layer subprotocols like STOMP or JSON-RPC.
RFC 6455 HANDSHAKE WIRE PROTOCOL:
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 1. CLIENT INITIATES UPGRADE OVER TCP: │
│ GET /v1/live-feed HTTP/1.1 │
│ Host: stream.nikita-infotech.com │
│ Upgrade: websocket │
│ Connection: Upgrade │
│ Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== │
│ Sec-WebSocket-Version: 13 │
│ Sec-WebSocket-Protocol: json-v1, stomp │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼ (Server verifies and generates Accept Hash)
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 2. CRYPTOGRAPHIC PROOF COMPUTATION: │
│ Guid String : 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 (Constant RFC 6455 UUID) │
│ Concatenate : "dGhlIHNhbXBsZSBub25jZQ==" + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" │
│ Calculation : Base64(SHA-1(Concatenated String)) │
│ Yields : s3pPLMBiTxaQ9kYGzzhZRbK+xOo= │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 3. SERVER RESPONDS WITH 101 SWITCHING PROTOCOLS: │
│ HTTP/1.1 101 Switching Protocols │
│ Upgrade: websocket │
│ Connection: Upgrade │
│ Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= │
│ Sec-WebSocket-Protocol: json-v1 │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────────────────────────────────────────┐
│ 4. BI-DIRECTIONAL DUPLEX ACTIVE: Plain HTTP connection terminates; WebSocket frames begin. │
└───────────────────────────────────────────────────────────────────────────────────────────────┘
RFC 6455 BINARY FRAME STRUCTURE:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+---------------------------------------------------------------+
STANDARD WEBSOCKET OPCODES:
┌────────┬─────────────┬────────────────────────────────────────────────────────────────────────┐
│ OPCODE │ TYPE │ SEMANTIC BEHAVIOR │
├────────┼─────────────┼────────────────────────────────────────────────────────────────────────┤
│ 0x0 │ Continuation│ Continues a fragmented message stream │
│ 0x1 │ Text Frame │ UTF-8 text payload (standard JSON, strings) │
│ 0x2 │ Binary Frame│ Raw bytes (Protobuf, Avro, images, audio streams) │
│ 0x8 │ Close │ Initiates or acknowledges graceful connection teardown (with status) │
│ 0x9 │ Ping │ Heartbeat probe sent to confirm remote peer is alive │
│ 0xA │ Pong │ Immediate reply to Ping frame with identical payload data │
└────────┴─────────────┴────────────────────────────────────────────────────────────────────────┘
-- 1. POSTMAN WEBSOCKET CONNECTION SPECIFICATION --
URL: wss://stream.nikita-infotech.com/v1/students/live
Headers:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsIn...
X-Client-Version: 2026.1
-- 2. CLIENT OUTGOING MESSAGE (SEND RAW JSON): --
{
"action": "SUBSCRIBE_STUDENT_EVENTS",
"studentId": "STU-88219",
"events": ["COURSE_ENROLLED", "SCORE_UPDATED"]
}
-- 3. SERVER ASYNCHRONOUS INCOMING MESSAGE STREAM (CAPTURED IN POSTMAN TIMELINE): --
# Message 1 (Immediate subscription acknowledgement):
{
"event": "SUBSCRIPTION_CONFIRMED",
"subscriptionId": "SUB-9912048",
"timestamp": 1793524800
}
# Message 2 (Asynchronous push event triggered 2 seconds later):
{
"event": "SCORE_UPDATED",
"studentId": "STU-88219",
"courseCode": "API-PRO-101",
"newGpa": 3.95,
"updatedAt": "2026-11-01T13:10:02Z"
}
-- 4. POSTMAN POST-RESPONSE SCRIPT ASSERTION (TESTS TAB): --
pm.test("Verify subscription confirmation message", function () {
const responseJson = pm.response.json();
pm.expect(responseJson.event).to.eql("SUBSCRIPTION_CONFIRMED");
pm.expect(responseJson.subscriptionId).to.match(/^SUB-[0-9]{7}$/);
});
websockets and pytest-asyncio to connect, send subscriptions, receive pushed frames, and assert contract compliance within timeout SLAs.
import asyncio
import json
import pytest
import websockets
WS_ENDPOINT = "wss://stream.nikita-infotech.com/v1/students/live"
AUTH_TOKEN = "mock-active-bearer-token-2026"
@pytest.mark.asyncio
class TestWebSocketEventStreaming:
async def test_websocket_connect_and_receive_event(self):
"""Validates connection handshake, event subscription, and event delivery within 3.0s."""
headers = {"Authorization": f"Bearer {AUTH_TOKEN}"}
# 1. Establish persistent full-duplex WebSocket connection
async with websockets.connect(WS_ENDPOINT, extra_headers=headers, timeout=5.0) as ws:
assert ws.open, "WebSocket connection failed to open!"
# 2. Dispatch client subscription message
subscribe_payload = {
"action": "SUBSCRIBE",
"studentId": "STU-88219"
}
await ws.send(json.dumps(subscribe_payload))
print(f"\n[*] Dispatched subscription: {subscribe_payload}")
# 3. Await server acknowledgement frame (bounded by 3.0s SLA)
ack_raw = await asyncio.wait_for(ws.recv(), timeout=3.0)
ack_data = json.loads(ack_raw)
assert ack_data.get("event") == "SUBSCRIPTION_CONFIRMED"
assert "subscriptionId" in ack_data
print(f"[+] Received ACK: {ack_data['subscriptionId']}")
# 4. Await asynchronous server push event
push_raw = await asyncio.wait_for(ws.recv(), timeout=5.0)
push_data = json.loads(push_raw)
assert push_data.get("studentId") == "STU-88219"
assert "newGpa" in push_data
print(f"[+] Verified Push Event: Score updated to {push_data['newGpa']}")
# 5. Clean teardown with standard close frame (1000 Normal Closure)
await ws.close(code=1000, reason="Test Completed Successfully")
assert ws.closed
0x9 and 0xA) to prevent intermediate proxies, firewalls, and gateways from dropping idle TCP connections.
import asyncio
import pytest
import websockets
@pytest.mark.asyncio
async def test_ping_pong_heartbeat_roundtrip():
"""Sends a raw Ping frame and asserts the server replies with matching Pong frame."""
uri = "wss://stream.nikita-infotech.com/v1/heartbeat"
async with websockets.connect(uri) as ws:
# 1. Custom binary heartbeat token
ping_payload = b"\x01\x02\x03\x04_HEARTBEAT"
# 2. Transmit Ping frame (Opcode 0x9)
pong_waiter = await ws.ping(data=ping_payload)
print("\n[*] Dispatched Ping frame with 16-byte nonce...")
# 3. Assert server returns corresponding Pong frame (Opcode 0xA) within 2.0s
await asyncio.wait_for(pong_waiter, timeout=2.0)
print("[+] Pong frame confirmed: Server heartbeat verified alive!")
# 4. Negative Test: Test connection health after simulated idle timeout
# An unmaintained connection with no ping/pong should be closed by server with code 1006
await asyncio.sleep(0.5)
assert ws.open, "Connection dropped prematurely!"
-- STEP 1: CLIENT SENDS STOMP 'CONNECT' FRAME INSIDE WEBSOCKET TEXT FRAME --
CONNECT
accept-version:1.2,1.1
host:stream.nikita-infotech.com
heart-beat:10000,10000
Authorization:Bearer mock-token-99214
^@
-- STEP 2: SERVER EMITS STOMP 'CONNECTED' FRAME --
CONNECTED
version:1.2
heart-beat:10000,10000
session:session-k992140a
^@
-- STEP 3: CLIENT SUBSCRIBES TO DESTINATION TOPIC --
SUBSCRIBE
id:sub-01
destination:/topic/course.updates.API-PRO-101
ack:auto
^@
-- STEP 4: SERVER ASYNCHRONOUSLY PUSHES BROKER MESSAGE TO TOPIC --
MESSAGE
destination:/topic/course.updates.API-PRO-101
subscription:sub-01
message-id:msg-881920
content-type:application/json
{"courseCode":"API-PRO-101","event":"SEATS_REMAINING","seats":3}
^@
-- NOTE: '^@' denotes the ASCII NUL byte (0x00) marking the end of every STOMP frame. --
package com.nikitainfotech.api.websocket;
import org.glassfish.tyrus.client.ClientManager;
import org.testng.Assert;
import org.testng.annotations.Test;
import jakarta.websocket.*;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ClientEndpoint
public class JavaTyrusWebSocketTest {
private Session session;
private String receivedMessage;
private static CountDownLatch messageLatch;
@OnOpen
public void onOpen(Session session) {
this.session = session;
System.out.println("[+] Sockets Connected: Session ID " + session.getId());
}
@OnMessage
public void onMessage(String message) {
System.out.println("[+] Received Incoming Frame: " + message);
this.receivedMessage = message;
messageLatch.countDown(); // Unblock awaiting test thread
}
@OnClose
public void onClose(Session session, CloseReason reason) {
System.out.println("[-] Socket Closed: " + reason.getReasonPhrase());
}
@Test
public void testWebSocketLifecycleJava() throws Exception {
messageLatch = new CountDownLatch(1);
ClientManager client = ClientManager.createClient();
URI serverUri = new URI("wss://stream.nikita-infotech.com/v1/students/live");
// 1. Connect client endpoint to remote server
Session activeSession = client.connectToServer(this, serverUri);
Assert.assertTrue(activeSession.isOpen(), "Session should be open!");
// 2. Dispatch test message over the wire
String outgoingPayload = "{\"action\":\"PING_STUDENT\",\"id\":\"STU-88219\"}";
activeSession.getBasicRemote().sendText(outgoingPayload);
// 3. Await message delivery using CountDownLatch with 4.0s SLA
boolean messageReceivedInTime = messageLatch.await(4, TimeUnit.SECONDS);
Assert.assertTrue(messageReceivedInTime, "Timed out waiting for server event frame!");
// 4. Assert response payload contents
Assert.assertNotNull(receivedMessage);
Assert.assertTrue(receivedMessage.contains("STU-88219"));
// 5. Clean teardown
activeSession.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Test Complete"));
}
}
wiremock-webhooks-and-websocket extension to stub handshakes and simulate push streams.
{
"request": {
"method": "GET",
"url": "/v1/live-feed",
"headers": {
"Upgrade": {
"equalTo": "websocket"
},
"Connection": {
"equalTo": "Upgrade"
}
}
},
"response": {
"status": 101,
"headers": {
"Upgrade": "websocket",
"Connection": "Upgrade"
}
},
"postServeActions": [
{
"name": "websocket-push",
"parameters": {
"delay": 200,
"frames": [
{
"type": "TEXT",
"body": "{\"event\":\"STREAM_STARTED\",\"clusterId\":\"IN-PUNE-1\"}"
},
{
"type": "TEXT",
"delay": 500,
"body": "{\"event\":\"SCORE_ALERT\",\"studentId\":\"STU-88219\",\"gpa\":3.95}"
}
]
}
}
]
}
RFC 6455 WEBSOCKET CLOSE CODES & TESTING ASSERTIONS:
┌──────┬─────────────────────────────┬─────────────────────────────────────────────────────────────────┐
│ CODE │ STATUS NAME │ SCENARIO OCCURRENCE & EXPECTED CLIENT BEHAVIOR │
├──────┼─────────────────────────────┼─────────────────────────────────────────────────────────────────┤
│ 1000 │ Normal Closure │ Purpose fulfilled; intentional teardown. DO NOT reconnect. │
│ 1001 │ Going Away │ Server shutting down or navigating away. Reconnect after delay │
│ 1002 │ Protocol Error │ Frame violation (e.g. unmasked client frame). DO NOT retry. │
│ 1003 │ Unsupported Data │ Binary sent to text-only endpoint. DO NOT retry. │
│ 1006 │ Abnormal Closure │ Socket abruptly severed without close frame (crash/network). │
│ │ │ CLIENT MUST: Trigger exponential backoff reconnection loop. │
│ 1008 │ Policy Violation │ Authentication expired or rate limit breached. Re-auth first. │
│ 1009 │ Message Too Big │ Exceeded max allowed frame size (e.g. > 16MB). Reject input. │
│ 1011 │ Internal Server Error │ Unhandled backend crash while processing frame. │
└──────┴─────────────────────────────┴─────────────────────────────────────────────────────────────────┘
RECONNECTION TEST ASSERTION CHECKPOINT:
1. Simulate server closing socket with code 1006 (Abnormal Closure).
2. Assert client catches Disconnected event.
3. Assert client initiates reconnect attempts at backoff intervals: 1s -> 2s -> 4s -> 8s.
4. Assert client re-subscribes to active topics once the socket is re-established.
WEBSOCKET PROTOCOL & TESTING REFERENCE MATRIX:
┌─────────────────────┬──────────────────────────────┬────────────────────────────────────────────────────┐
│ ELEMENT / CONCEPT │ PROTOCOL SPECIFICATION │ PRIMARY TESTING FOCUS & BEHAVIOR │
├─────────────────────┼──────────────────────────────┼────────────────────────────────────────────────────┤
│ HTTP 101 Switching │ RFC 6455 Handshake │ Validate Upgrade: websocket and Sec-WebSocket-Key │
│ Opcode 0x1 (Text) │ Data Framing │ Assert UTF-8 JSON message format and payload schema│
│ Opcode 0x2 (Binary) │ Data Framing │ Verify Protobuf/byte stream deserialization │
│ Opcode 0x9 (Ping) │ Heartbeat Frame │ Test connection keep-alive and network presence │
│ Opcode 0xA (Pong) │ Heartbeat Frame │ Verify server echoes exact binary payload back │
│ Code 1000 │ Normal Closure │ Confirm clean, voluntary connection termination │
│ Code 1006 │ Abnormal Closure │ Validate client exponential backoff reconnection │
│ STOMP Subprotocol │ Application Messaging │ Validate CONNECT, SUBSCRIBE, and MESSAGE frames │
│ websockets (Python) │ Client Library │ Fast async test execution via pytest-asyncio │
│ Tyrus (Java) │ JSR 356 Reference Client │ Robust Java WebSocket test suites with CountDown │
├─────────────────────┴──────────────────────────────┴────────────────────────────────────────────────────┤
│ TOP 5 WEBSOCKET AUTOMATION BEST PRACTICES: │
│ 1. Always use timeouts on recv(): Never let test threads hang indefinitely waiting for pushed frames. │
│ 2. Test ping/pong health checks: Verify connections stay alive through idle firewall timeouts. │
│ 3. Validate close codes: Confirm clean closures return 1000 and auth rejections return 1008. │
│ 4. Test reconnection logic: Sever sockets mid-test to assert that clients reconnect and re-subscribe. │
│ 5. Clean up open connections: Always close sockets in teardown hooks to avoid orphaned TCP sessions. │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────┘