I’ve used both of these protocols, but I’ve never compared them, so I’m going to compare them today.

HTTP

What is HTTP?

HTTP: HyperText Transfer Protocol. English: Hypertext Transfer protocol.

Features:

  • Based on TCP.
  • Stateless.

Let’s just briefly explain what statelessness is. Okay?

There is no connection between each request, meaning that the server does not know if each request is the same user.

Why is HTTP designed to be a stateless protocol?

That depends on his merits:

  • The first is to reduce server stress and free up the server so that each request does not cause unnecessary connection hogging.
  • Since each request is unrelated, if the first request fails, subsequent requests continue.

But there are drawbacks:

  • Each request creates an unnecessarily large number of duplicate content messages.

How do you solve this statelessness?

Cookie and Session solve the problem caused by HTTP stateless.

HTTP/1.1 default keep-alive

Long connection means that the TCP connection is kept open for data requests within a certain period of time.

For this section, see my previous article, “The Relationship between TCP and HTTP Requests.”

WebSocket

WebSocket protocol is H5, he and HTTP can not say that there is no relationship, should be said to be the intersection of relations.

HTTP does not support persistent connections, and WebSocket solves this problem.

Features:

  • WebSocket is built on top of TCP.

  • Good compatibility (intersection) with HTTP. For example, the default ports are 80 and 443, and the handshake is HTTP.

  • Persistence, as opposed to HTTP.

  • WebSocket has no same-origin restriction, and clients can communicate with any server.

Principle:

  • Part of the handshake is done based on HTTP.

  • The request header is as follows:

  •   Upgrade: websocket
      Connection: Upgrade
      Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
      Sec-WebSocket-Key: mg8LvEqrB2vLpyCNnCJV3Q==
      Sec-WebSocket-Version: 13
    Copy the code
  • Upgrade and Connection notify the server, and the browser initiates the WebSocket protocol.

  • Sec-websocket-extensions: indicates the protocol-level extension that the client wants.

  • Sec-websocket-key: Base64 encoded value randomly generated by the browser.

  • Sec-websocket-version: indicates the Version of the protocol used by the client.

  • The purpose of the request header is to inform the server to change the protocol to WebSocket. And use sec-websocket-key for confirmation.

  • The response header is as follows:

  •   Upgrade: websocket
      Connection: Upgrade
      Sec-WebSocket-Accept: AYtwtwampsFjE0lu3kFQrmOCzLQ=
    Copy the code
  • Notify the browser that the rewrite was successful.

  • Sec-websocket-accept: Base64 encoded value returned by server encryption.

Conclusion:

HTTP and WebSocket were briefly introduced, and will be added here if there are more details.