{
    "slug": "websocket_protocol",
    "term": "WebSocket Protocol",
    "category": "networking",
    "difficulty": "intermediate",
    "short": "A full-duplex communication protocol over a single TCP connection — the client and server can both send messages at any time without polling.",
    "long": "WebSockets begin as an HTTP request with Upgrade: websocket header. After the server acknowledges, the connection upgrades to a persistent bidirectional TCP channel. Frames carry data in either direction — text or binary. Unlike HTTP request-response, the server can push data to the client at any time. The ws:// scheme is unencrypted; wss:// uses TLS. PHP WebSocket servers require a persistent process (Ratchet, Swoole, ReactPHP) since PHP-FPM terminates after each request.",
    "aliases": [
        "WebSockets",
        "ws://",
        "wss://",
        "full-duplex"
    ],
    "tags": [
        "networking",
        "websockets",
        "real-time",
        "php"
    ],
    "misconception": "PHP cannot do WebSockets — standard PHP-FPM cannot, but Swoole, Ratchet (ReactPHP), and OpenSwoole all support WebSocket servers in PHP.",
    "why_it_matters": "Real-time features (live chat, collaborative editing, live dashboards) require the server to push updates — WebSockets enable this without client polling overhead.",
    "common_mistakes": [
        "Using WebSockets for request-response patterns — HTTP is more appropriate; WebSockets suit continuous bidirectional streams.",
        "No heartbeat/ping — idle WebSocket connections are silently dropped by load balancers; send periodic pings.",
        "No authentication on the WebSocket connection — validate a token during the upgrade handshake before accepting the connection.",
        "Not handling reconnection — connections drop; clients must implement exponential backoff reconnection logic."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "websockets",
        "long_polling",
        "swoole_openswoole",
        "php_async_frameworks"
    ],
    "prerequisites": [
        "tcp_ip_model",
        "http_request_response_cycle",
        "long_polling_sse"
    ],
    "refs": [
        "https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API"
    ],
    "bad_code": "// No authentication on WebSocket upgrade:\n$server->on('open', function(ConnectionInterface $conn) {\n    $this->clients->attach($conn);\n    // Anyone who connects receives all messages — no auth check\n});",
    "good_code": "// Authenticate during upgrade:\n$server->on('open', function(ConnectionInterface $conn) {\n    $request = $conn->httpRequest;\n    $token = $request->getQueryParams()['token'] ?? '';\n    if (!$this->auth->validateToken($token)) {\n        $conn->close();\n        return;\n    }\n    $userId = $this->auth->getUserId($token);\n    $this->clients[$userId] = $conn;\n});",
    "quick_fix": "For PHP, use Laravel Reverb (native) or Soketi (self-hosted Pusher-compatible) rather than implementing WebSocket from scratch — they handle the protocol complexity and integrate with Laravel events",
    "severity": "medium",
    "effort": "high",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/websocket_protocol",
        "html_url": "https://codeclaritylab.com/glossary/websocket_protocol",
        "json_url": "https://codeclaritylab.com/glossary/websocket_protocol.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[WebSocket Protocol](https://codeclaritylab.com/glossary/websocket_protocol) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/websocket_protocol"
            }
        }
    }
}