is websocket protocol built on top of http protocol
WebSockets are not accurately described as either a "top-level protocol above HTTP" or a "low-level" protocol in relation to HTTP. Instead, WebSockets represent a distinct communication protocol designed to work alongside HTTP, complementing it by providing capabilities that HTTP does not inherently support, such as persistent, full-duplex communication channels between a client and a server.
Relationship with HTTP
-
Initialization Over HTTP: The WebSocket protocol initiates its connection by using an HTTP handshake, an upgrade request that switches the protocol from HTTP to WebSocket. This handshake is sent by the client as an HTTP request that includes an "Upgrade: websocket" header, signaling the server that the client wishes to establish a WebSocket connection. If the server supports WebSockets and accepts the request, it responds with an HTTP 101 status code, indicating that the protocol is switching from HTTP to WebSocket.
-
Protocol Upgrade: After the handshake, the communication protocol upgrades from HTTP to WebSocket, enabling a persistent, full-duplex communication channel. This means that, unlike HTTP, which is a stateless protocol where each request/response pair is independent, a WebSocket connection allows for continuous two-way communication after the initial handshake.
Not Above or Below HTTP, but Complementary
-
Complementary Protocol: WebSockets are designed to complement HTTP by providing capabilities for real-time communication that HTTP, by its design, cannot efficiently offer. While HTTP is perfect for document exchange and stateless RESTful services, WebSockets are tailored for real-time, bidirectional communication often required by web applications like gaming, chat applications, and live sports updates.
-
Different Use Cases: It's not accurate to think of WebSockets as higher or lower in a hierarchical sense compared to HTTP. Instead, they serve different purposes. HTTP is ideal for request-response interactions, where the initiation is always from the client. WebSockets, on the other hand, allow either the client or server to initiate communication, which is essential for real-time applications.
Technical Perspective
- Separate Protocol: Technically, WebSocket is a separate protocol from HTTP, defined by the IETF as RFC 6455. Although it starts with an HTTP handshake for compatibility with HTTP servers, once the WebSocket connection is established, it no longer operates under the constraints of HTTP and does not use HTTP for data transfer.