Recently, colleagues in the company shared some knowledge about WebSocket, and I used WebSocket to make an instant messaging application. Basically, any mention of WebSocket and HTTP relationship will have the following two:

WebSocket and HTTP are two different protocols based on TCP. WebSocket relies on HTTP connections

As a conclusion, it is straightforward, but I need more implementation details to explain the above conclusions. Since these are two separate protocols based on TCP, WebSocket is supposedly independent of HTTP, so there are two problems with this:

WebSocket relies on HTTP connections. How does it convert a connection’s HTTP protocol to WebSocket? Why does WebSocket rely on HTTP connections?

Problem a

Fortunately, the answer to the first question is easy to find.

Each WebSocket connection starts with an HTTP request. Specifically, the WebSocket protocol sends the WebSocket supported version number, protocol version number, original address, host address and other columns to the server during the first handshake connection through HTTP:

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key:dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Version: 13
Copy the code

The Upgrade header is used to Upgrade current HTTP requests to the WebSocket protocol, which is part of the HTTP protocol itself and is extended to support other communication protocols. If the server supports the new protocol, you must return 101:

HTTP / 1.1101 Switching separate Protocols Upgrade: websocket Connection: Upgrade the Sec - websocket - Accept: s3pPLMBiTxaQ9kYGzzhZRbK + xOo =Copy the code

At this point, the HTTP request is used, if the onopen event is successfully launched, otherwise the onError event is raised, and the subsequent transmission no longer depends on the HTTP protocol. To summarize, this graph is apt:

Question 2

After learning and understanding, I think there are two points:

First, WebSocket is designed by nature to enhance HTTP communication (full-duplex communication, etc.), so it is natural to build on HTTP connections and thus get many of the benefits of HTTP. Second, one of the most important of these conveniences is that http-based connections will get maximum compatibility support, such as the ability to establish HTTP communication even if the server does not support WebSocket, but only returns onError, which is obviously better than a server that does not respond.

The last

There is a lot of discussion about WebSocket and HTTP on the Web, but because some of the information is inherently illogical, the more you look at it, the more confused you may become about their relationship. Untangling this simple relationship is necessary to understand their application scenarios, which is the starting point for my analysis.