Detailed explanation and use of instant messaging WebSocket

Due to  http an obvious drawback (messages can only be pushed to the server by the client, but cannot be actively pushed to the client by the server), if the server has continuous changes, only polling can be used at this time, and the polling efficiency Too low and not suitable. So  WebSocketit was invented.

Table of contents

​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Two, the characteristics of WebSocket

3. The communication principle and mechanism of WebSocket

4. What are the advantages of WebSocket compared to http

Five, the difference between short polling, long polling and WebSocket

Six, WebSocket handshake

7. WebSocket usage and usage scenarios


​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

   ​​​​​​​​ WebSocket is a protocol for full-duplex communication on a single TCP connection . Data is transmitted through the http protocol, but after the connection is established, the real data transmission stage does not require the participation of the http protocol . Both the client and the server can send data to each other at any time, which can better save server resources and bandwidth and achieve the purpose of real-time communication.

Two, the characteristics of WebSocket

           1. WebSocket adopts a binary frame structure, and its syntax and semantics are completely incompatible with HTTP. However, because its main operating environment is a browser, its usage habits are as close as possible to HTTP.

          2. WebSocket does not use the "IP address + port number" of TCP. WebSocket uses ws or wss protocol, which represent plain text and encrypted WebSocket protocol respectively.

3. The communication principle and mechanism of WebSocket

          WebSocket stipulates a communication specification. Through a handshake mechanism, a client and server can establish a long-term connection similar to a tcp server, and data transmission is bidirectional.

4. What are the advantages of WebSocket compared to http

Advantages of websockets:

  • ​​​​​​​​Support two-way communication, more real-time;
  • You can send text or binary files;
  • The protocol identifier is ws, which is wss after encryption;
  • Less control overhead. After the connection is established, when the ws client and server exchange data, the header of the data packet controlled by the protocol is small. In the case of not including the header, the packet header from the server to the client is only 2~10 bytes (depending on the length of the data packet), and from the client to the server, an additional 4-byte mask is required. The HTTP protocol needs to carry a complete header every time it communicates;
  • Support for extensions. The ws protocol defines extensions, and users can extend the protocol or implement custom sub-protocols. (such as support for custom compression algorithms, etc.)
  • No cross domain issues.

Same point:

  • Both are based on tcp, and they are all reliable transmission protocols.
  • are application layer protocols

difference:

  • WebSocket is a two-way communication protocol, simulating the Socket protocol, which can send or receive information in both directions
  • HTTP is one-way
  • WebSocket requires a handshake between the browser and the server to establish a connection
  • And http is a connection initiated by the browser to the server, and the server does not know this connection in advance.

Contact: When WebSocket establishes a handshake, data is transmitted via HTTP. But after the establishment, the HTTP protocol is not required for real transmission

Five, the difference between short polling, long polling and WebSocket

1. Short Polling

The basic idea of ​​short polling:
the browser sends http requests to the browser every once in a while, and the server responds directly after receiving the request, regardless of whether there is data update.
The instant messaging implemented in this way is essentially a process in which the browser sends a request and the server accepts the request. By making the client make continuous requests, the client can simulate real-time data changes received from the server.
Advantages and disadvantages
The advantage is that it is relatively simple and easy to understand.
The disadvantage is that this method seriously wastes the resources of the server and client due to the need to continuously establish http connections. When the number of users increases, the pressure on the server side will increase, which is very unreasonable.

2. Long polling

​​​​​​​​The basic idea of ​​long
first, the client initiates a request to the server. When the server receives the request from the client, the server will not respond directly, but hangs the request first. Start, and then determine whether the server-side data has been updated.
If there is an update, it will respond. If there is no data, it will return after reaching a certain time limit. After processing the information returned by the server, the client-side JavaScript response processing function will send a request again to re-establish the connection.
Advantages
and disadvantages Compared with short polling, long polling has the advantage of significantly reducing the number of unnecessary http requests, and saving resources in comparison.
The disadvantage of long polling is that the connection hang will also lead to a waste of resources

3. WebSocket

​​​​​​​​WebSocket is a new protocol defined by Html5. Different from the traditional http protocol, this protocol allows the server to actively push information to the client.
The disadvantage of using the WebSocket protocol is that the configuration on the server side is more complicated. WebSocket is a full-duplex protocol, that is, both parties to the communication are equal and can send messages to each other.

Six, WebSocket handshake

As can be seen from the picture, there are three stages

  • open handshake
  • data transfer
  • close handshake

TCP handshake

Both the client and the server need to wait until they can send and receive, so a three-way handshake is required

three handshake 

  • The first successful handshake lets the server know that the client has the ability to send
  • The success of the second handshake lets the client know that the server has the ability to receive and send, but at this time the server does not know whether the client has received the message it sent
  • So the third handshake does that. `

 

Can data be carried during the three-way handshake?

  • The first and second handshakes cannot carry data, because the connection has not been established during the first and second handshakes, which will make the server vulnerable to attacks
  • For the third handshake, the client is already in the state  ESTABLISHED (已建立连接状态) . For the client, the connection has been established, and it already knows that the server's receiving and sending capabilities are normal, so it is no problem to be able to carry data.

waved four times 

The so-called four-time wave is the release (release) of the TCP connection. The release of the connection must be actively released by one party and passively released by the other party

Only when the server has sent all the messages will it send a FIN message to tell the client that it can disconnect, so it needs to wave four times when disconnecting.

  • When closing the connection, when receiving the FIN message notification from the other party, it only means that the other party has no data to send to you; but not necessarily all your data has been sent to the other party
  • So you may not close it immediately SOCKET, that is, you may need to send some data to the other party, and then send a FIN message to the other party to express your agreement to close the connection now, so the messages here ACKand the FIN message are mostly are sent separately.

 

Why is it only three times to establish a connection, but four times to disconnect?

  • The client requests to disconnect and sends a disconnection request, which is called (FIN).
  • The server receives the request, and then gives the client an ACK as a response to the FIN.
  • Here you need to think about a question, can you upload FIN back immediately like a handshake?
  • In fact, the server cannot upload the FIN immediately at this time, because there are many problems to be dealt with when disconnecting. For example, the server may still have sent messages that have not been ACKed; it is also possible that the server has resources to release. So a disconnect cannot operate like a handshake - merge the two messages. So, 服务端经过一个等待,确定可以关闭连接了,再发一条 FIN 给客户端.
  • The client receives the FIN from the server, and the client may also have its own affairs to be processed. For example, the client sends a request to the server but does not receive an ACK. After the client completes the processing, it sends an ACK to the server. .

7. WebSocket usage and usage scenarios

1. Create a websocket object, and connect the client and server through the address.

The current state of websocket:
ws.readyState 
// 0: 'CONNECTING', indicating that it is connecting
// 1: 'OPEN', indicating that the connection is successful and communication is possible
// 2: 'CLOSING', indicating that the connection is closing
// 3: ' CLOSED', indicates that the connection has been closed, or failed to open the connection. ​​​​​​​​

// 创建WebSocket连接.
const socket = new WebSocket('ws://localhost:8080');

2. Triggered when the connection is successful

    Connection trigger event:

  • Socket.onopen: triggered when the connection is established
  • Socke.onmessage: Triggered when the client receives data from the server
  • Socket.onerror: Triggered when a communication error occurs
  • Socket.onclose: triggered when the connection is closed
ws.onopen = function () {
  // 指定连接成功后的回调函数
}         
ws.onclose = function () {
  // 指定连接关闭后的回调函数
}         
ws.onmessage = function () {
  // 指定收到服务器数据后的回调函数
}         
ws.onerror = function () {
  // 指定报错时的回调函数
}

3. Send data

ws.send(message)  向服务器发送数据

4. Close the connection

ws.close()  关闭当前连接

scenes to be used 

  • instant messaging
  • online game
  • Software update
  • live chat
  • social feed
  • Multi-person collaborative online editing

Guess you like

Origin blog.csdn.net/qq_52337177/article/details/127243229