Painted painted levels: fostered fostered fostered

Tag: “WebSocket” “Starscream” author: 647


* preface:

Some time ago, I used WebSocket in the company’s project, so I didn’t have time to sort it out properly. Recently, while I have time, I have combed the knowledge of WebSocket. *


** This article will introduce the following contents:

1. What is WebSocket? WebSocket usage scenarios 3. Basic principles of WebSocket (protocol) 4. Related frameworks of iOS WebSocket **


What is WebSocket?

WebSocket = HTTP first handshake +TCPA network protocol for “full duplex” communication.

Main process:

  • First of all, throughHTTPThe first handshake ensures a successful connection.
  • Second, pass againTCPImplement full duplex between browser and server (full-duplexCommunication). (By constantly sendingpingPackages,pangPackets keep the heartbeat)

Finally, the “server” has the ability to “proactively” send messages to the “client”.

Here are a few highlights:

  1. WebSocketIs based onTCPThe upper application layer network protocol.
  2. It depends on theHTTPAfter a successful first handshakeTCPTwo-way communication.

Two, WebSocket application scenarios

1. IM

Typical examples: wechat, QQ, etc. Of course, if the number of users is very large, it is certainly not enough to rely on WebSocket only, and major factories should also have their own optimization plans and measures. However, WebSocket is a good solution for instant messaging with small users.

2. Games (multiplayer)

Typical example: King of Glory, etc.

3. Collaborative editing (sharing documents)

When multiple people edit the same document at the same time, they can see each other’s actions in real time. In this case, WebSocket is used.

Live/video chat

High real time requirement for audio/video.

5. Stock/fund and other financial trading platforms

For stock/fund trading, the price can change from second to second.

6. IoT (Internet of Things/Smart Home)

For example, our App needs to obtain the data and status of smart devices in real time. In this case, you need to use WebSocket.

. Etc., etc.

As long as some of the “real time” requirements are relatively high, may use WebSocket.


Third, the underlying principle of WebSocket

WebSocket is an application layer protocol on the network. It relies on the first handshake of HTTP. After the handshake is successful, data is transmitted through TCP/IP.

WebSocket consists of the handshake phase and the data transmission phase, that is, the TCP connection with HTTP handshake + duplex.

1. Handshake phase

First, the client sends a message:

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

The server then returns the message:

HTTP / 1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Copy the code

Base64 (HSA1 (SEC-websocket-key + 258eAFa5-E914-47DA-95CA-C5AB0DC85b11))

  • If theSec-WebSocket-AcceptIf the calculation is incorrect, the browser will prompt:Sec-WebSocket-Accept dismatch;
  • If success is returned,WebsocketWill the callbackonopenThe event

2. Transmission phase

WebSocket transmits data in the form of a frame. For example, a message is divided into frames and transmitted in sequence.

This has several benefits:

  • Large data can be transmitted in fragments without considering the insufficient length flag bits caused by data size.
  • andHTTPthechunkSimilarly, messages can be delivered while generating data, which increases transmission efficiency.

The packets used in WebSocket transmission are as follows:

The parameters are described as follows:

  • FIN (1 bit) :

Represents the last frame of the message, a flag, which is a marker. PS: Of course, the first message fragment could also be the last message fragment;

  • RSV1, RSV2, RSV3 (all 1 bit) :

The default value is 0. If there is a custom protocol, the value is not 0. Generally, the value is 0. (Protocol extension)

  • Opcode (4 bit) :

Define the payload data. If an unknown opcode is received, the connection must also be broken. The following opcodes are defined:

opcode meaning
%x0 Continuous message fragment
%x1 Text message fragment
%x2 Binary message fragment
%x3-7 (reserved bit) An opcode reserved for future non-control message fragments.
%x8 Connection is closed
%x9 Heartbeat Check Ping
%xA Heartbeat check PONG
%xB-F (reserved bit) Reserved opcodes for future control message fragments.
  • Mask (1 bit) :

Whether to add a mask for transmitting data. If the value is 1, the mask must be placed in the masking-key area. (More on that later) Note: The Mask value of messages sent from the client to the server is 1.

  • Payload length:

The Payload field stores the length of transmitted data.

The Payload field size can be 7 bits, 7+16 bits, or 7+64 bits.

Type 1:7 bits: 0000000 to 1111101 (0 to 125), which indicates the length of the current data (the maximum length of the small data is 125).

Second: (7+16) bit: the first seven bits are 1111110 (126). 126 represents the unsigned number followed by two bytes, which is used to store the length of the data (the minimum length is 126 and the maximum length is 65 535).

The third type: (7+64) bit: the first 7 bits are 1111111 (127), which is followed by 8 bytes of unsigned number. 127 is used to store the length of data (the minimum length is 65536, the maximum is 2^16-1).

Payload Packet Length The size range of data transferred
7 bit [0, 125]
7 +16 bit [126, 65535]
7 + 64 bit [] 2 ^ 16-65536),”

Description:

The length of the transmitted data, expressed in bytes: 7 bits, 7+16 bits, or 7+64 bits. 1) If the value is in the range 0-125 in bytes, the value represents the length of the data transferred; 2) If the value is 126, the following two bytes represent a hexadecimal unsigned number that represents the length of the transmitted data; 3) If the value is 127, it is followed by an 8-byte representation of a 64-bit unsigned number, which is used to indicate the length of the data being transferred.

  • Masking-key (0 bit / 4 bit) :

0 bit: indicates that the mask value is not 1 and there is no mask. 4 bit: If the mask value is 1, add the mask.

PS: Mask is 1 when the client sends data to the server.

At the same time, Masking-key stores a 32-bit mask.

  • Payload Data (x+y byte) :

Load data is the sum of extended data and application data.

  • Extension Data (x byte) :

If there is no special agreement between the client and the server, the length of the extended data is always 0, and any extension must specify the length of the extended data, or how to calculate the length, and how to determine the correct handshake when shaking hands. If there is extended data, it is included in the length of the payload data.

  • Application Data (y byte) :

Any application data is placed after the extension data. Application data length = Payload data length – Extended data length Application data = Payload data-extension data


4. WebSocket framework in iOS

WebSocket (iOS client) :
  • Starscream (Swift)

Websockets in iOS and OSX. (STAR 5K +)

  • SocketRocket (Objective-c) :

Note: A conforming Objective-C WebSocket Client library. (STAR: 8K +)

  • SwiftWebSocket (Swift) :

Fast Websockets in iOS and OSX. (STAR: 1K +)

Socket (iOS client) :
  • CocoaAsyncSocket:

Asynchronous Socket Networking Library for Mac and iOS. (STAR: 11K +) Asynchronous Socket Networking Library for Mac and iOS. (STAR: 11k+)

  • Socket. IO – the client – swift:

Socket.IO- Client for iOS/OS X. (Star: 4k+)

In the next article, we’ll write a simple client WebSocket Demo using Starscream.

Related references:

“Wechat,QQ this kind of IM APP how to do – talk about Websocket” (frost big guy) “Websocket implementation principle” ‘


Recommended articles:

Using Swift for Bezier curve drawing Swift 5.1 (11) – Method Swift 5.1 (10) – Properties iOS App background Keep live Strange dance weekly