01. Introduction to webSocket

1. What is websocket?

Wikipedia: WebSocket is a different protocol than HTTP. Both are at the APPLICATION layer of the OSI model, and both rely on TCP at the transport layer.

In fact, Websocket is a “protocol”. Websocket uses HTTP to establish connections, but it is not based on HTTP.

2. Why websocket? In what scenario?

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client.

2.1 Communication mode between HTTP and Websocket

  • Websocket is two-way communication, using HTTP request-response mode interaction only in the case of the initial connection, and two-way communication after the connection is established.
  • HTTP is all one-way request-response communication.
  • Websocket two-way communication is more efficient than HTTP one-way communication.

2.2 Why WebSocket is Used?

  • HTTP does not support long connections. The new HTTP protocol may supportkeep aliveBut just keep the connection, that is, in an HTTP1.1 connection, you can send multiple requests and receive multiple responses. But each Request = Response is constant in HTTP and Response is passive, so you can’t actively send Response.
  • Support two-way communication, with stronger communication capability. The server can actively push, and the client can communicate with the server in real time.
  • Less resource overhead. When websocket establishes a connection, the packet Header controlled by the communication protocol is smaller, saving a lot of overhead.

2.3 Application Scenarios

  • Web game development, end-to-end real-time communication
  • Web chat
  • Stock quotes and other similar real-time push