What is a socket? Socket is not actually a protocol. It works at the OSI model session layer (Layer 5) and is an abstraction layer that exists to make it easier for people to use lower-level protocols (typically TCP or UDP) directly. A Socket is the encapsulation of TCP/IP. The Socket itself is not a protocol but an API.

What is WebSocket?

Websocket is an application layer protocol at the seventh layer of the application layer. It must use HTTP to hold a handshake. After the handshake is successful, data is directly transmitted through the TCP channel, regardless of HTTP. Websocket transmits data in the form of frames. For example, a message is divided into several frames and transmitted in sequence. In this way, there are several advantages: 1. The transmission of big data can be transmitted in fragments without considering the insufficient length marker bits caused by the data size. 2 Like HTTP chunk, data can be generated and messages can be transmitted at the same time, which improves transmission efficiency.

SocketRocket framework

Import the SocketRocket framework using Cocoapods

platform :ios,"7.0"

target "WebScoketTest" do
pod 'SocketRocket'

end
Copy the code

The framework is not open source and we can only see a few ways to encapsulate it. Part of the SRWebSocket initialization, as well as connection, close connection, send messages and other methods. The other part is SRWebSocketDelegate, which includes some callbacks: a callback to receive a message, a callback to fail the connection, a callback to close the connection, a callback to receive Pong, and a proxy method to see if a data message needs to be converted to string.

Using a framework

Examples include a simple heartbeat, reconnection mechanism, and pingpong mechanism wrapped in WebSocket:

(2) What is pingpong?

(3) What is the reconnection mechanism?

In theory, a Scoket connection that we voluntarily disconnect (e.g. logging out of an account, logging out of an APP to the background, etc.) should not need to be reconnected. All the other connections are disconnected, so we need to disconnect and reconnect. The usual solution is to try to reconnect a few times, and if that still fails, never reconnect again.

Implementation of webSocket server

(1) Install Homebrew

Terminal operation:

// Link 1 $ruby-e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Copy the code
(2) Install the Node

$ brew install node

(3) Install the WS module

$NPM install ws if an error occurs

npm WARN enoent ENOENT: no such file or directory

$NPM init -f

(4) The CD arrivesDownload the jsFile path

$node filenames.js to run the downloaded demo, try it!