The basic principle websocket

  • HTTP in a request can be only one response. And the response is passive, can not initiate
    • Therefore, past service side push information is kept by the client to achieve the polling
  • websocket is a two-way communication protocol that provides server capacity to take the initiative to push information
  • Websocket need to create a connection, which makes it become a stateful protocol, status information may be omitted after partial communication. The stateless HTTP requests may need to have to carry the state information (such as authentication, etc.) in each request
  • The default port is 80 and 443
  • Need client (browser) and server support both
  • If after the agent, then the agent also need support, otherwise some agents will automatically disconnect when a long time without communication
    • Therefore in order to ensure WS connection is not cut off, it will send a heartbeat
  • After WebSocket connection is established, the subsequent data are transmitted in the form of a sequence of frames
    • HTTP is only responsible for establishing the WebSocket connection
    • HTTP header does not need to send the subsequent data can be exchanged
      • Improve the efficiency of information exchange

[Pictures of foreign chains dumping fails, the source station may have security chain mechanism, it is recommended to save the picture down uploaded directly (img-orBOqaVO-1578405029023) (/ Users / wuwentao / Library / Application Support / typora-user-images / image-20200107213754408 .png)]

  • Websocket is based on the HTTP protocol, or borrow the HTTP protocol to complete part of the handshake
    • Sec-WebSocket-KeyIs a browser-generated Base64 value for the server to verify the validity of
    • Sec-WebSocket-AcceptAfter the server is identified and encryptedSec-WebSocket-Key
      • Will be Sec-WebSocket-Keywith 258EAFA5-E914-47DA-95CA-C5AB0DC85B11stitching
      • Calculated by SHA1 digest, and turn into a base64 string.
  • After the completion status code in response to http requests 101, showing switching protocol
    • Description WebSocket protocol to establish TCP transport layer connection via http protocol, after they have nothing to do with the http protocol
// 客户端请求
GET ws://example.com/ HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://example.com

// 服务器应答
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
Published 161 original articles · won praise 19 · views 50000 +

Guess you like

Origin blog.csdn.net/winter_wu_1998/article/details/103882450