This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging

More articles on my Github and personal public number [Whole cliff Road], welcome to watch [front knowledge points], if there is benefit, don’t pay, little hands point a Star

Read this article

  • Webscoket basics
  • Webscoket User guide

Real-time push technology

  • Real-time push technology can be implemented in two ways,Ajax pollingWebSocket
    • Ajax pollingIt sends HTTP requests to the server at a specified interval (for example, 1s) to obtain data and push data in real time. This traditional format has the obvious disadvantage that the client needs to constantly send requests to the server, which increases the server pressure
    • WebSocketProtocol, can better save server resources and bandwidth, and can be more real-time communication
  • Ws Handshake and data transfer image source: novice tutorial

A simple introduction

HTML 5 standard

  • HTML5New Protocols

Single TCP Connection

  • A protocol for full-duplex (sending and receiving at the same time) communication over a single TCP connection

Link based on HTTP

  • WebscoketIt’s not a brand New Deal, it’s a use ofHTTPProtocol to establish a connection (complete the handshake)
  • One handshake, permanent connection, two-way data transmission
  • This is a request by looking at the browserHTTPFor protocol-based GET requests, the handshake is performed only once, and then two-way data transfer can take place

There are no cross-domain issues

  • webscoketThe protocol itself does not require the same origin policy. Therefore, there is no cross-domain problem.
  • However, the browser will sendOriginHTTP headerTo the server, the server can be based onOriginTo refuse theWebSocketThe request. Therefore, whether the same origin is required depends on how the server checks.

Uniform Resource Identifier

  • wswss
  • According to the HTML5 standard there is a correspondenceHTTP -> ws; HTTPS -> wss

The heartbeat detection

  • The browser will not maintain the connection for you. You need to add a heartbeat monitor to keep the channel open

Break line reconnection

  • It is caused by network or server instabilitywebscoketThe cable is disconnected and needs to be reconnected

Property (if a Webket instance has been created)

  • Socket.readyState: read-only propertyreadyStateIndicates connection status
    • 0 – Indicates that the connection has not been established.
    • 1 – Indicates that the connection is established and communication is available.
    • 2 – Indicates that the connection is being closed.
    • 3 – Indicates that the connection is closed or cannot be opened.
  • Socket.bufferedAmount: read-only propertybufferedAmountHas beensend()Put the number of utF-8 text bytes that are in the queue for transmission, but have not yet been sent. This property can also be used to determine whether the Webscoket data has been sent.

Method (if a Webket instance has been created)

  • Socket.onopen: triggered when the connection is established
  • Scoket.onmessage: Triggered when the client receives data from the server
  • Scoket.onerror: triggered when a communication error occurs
  • Scoket.onclose: triggered when the connection is closed

handshake

  • A handshake request
GET /chat HTTP/1.1 Host: server.xxx.com Connection: Upgrade Sec-websocket-key: XXXX sec-websocket-key: XXXX sec-websocket-key: XXXX sec-websocket-key: XXXX chat, superchat Sec-WebSocket-Version: 13 // Indicates the WebSocket version. If the server does not support this version, it will return the sec-Websocket-versionheader, which contains the version Origin: http://xxx.com that the server supportsCopy the code
  • Compared with a normal HTTP request, it has two more parametersUpgrade: websocketConnection: UpgradeThese two arguments tell the server that I am making a Websocket request.

Using Webscoket

Create an instance

  • var Socket = new WebSocket(url, [protocol]);
    • The first parameter, URL, specifies the URL of the connection
    • The second parameter, protocol, is optional and specifies an acceptable subprotocol

Send a message

  • Send a message to the server after the link is successful (in JSON format)
Socket.onopen = function(){
  // Web Socket 已连接上,使用 send() 方法发送数据
  let params = {
  		data: '测试发送数据'
	}
  Socket.send(JSON.stringify(params))
  alert("数据发送中...")
}
Copy the code

Receives the message

  • Receive server push messages (JSON format) using webSocket built-in methods
Socket. Onmessage = function (e) {let res = json.parse (e.ata) alert(" data received... )}Copy the code

Close the connection

  • Error occurred or the connection was actively closed
Socket.onclose = function(){// close websocket alert(" connection closed..."). )}Copy the code

WebScoket usage note

The heartbeat detection

  • In the process of data transmission, WebScoket will encounter the situation of network disconnection or disconnection without sending data for a long timeonclose()The callback will not be triggered, in which case the data will be lost if it continues to be sent.
  • In order to avoid this, without using a third party WebScoket JS, we need to do our own heartbeat detection to avoid dropping and sending data continuously.

Break line reconnection

  • Disconnection reconnection is so that when the Websocket disconnects, it can make its own reconnection request and resume data transfer between the client and the server.

The next article will walk you through WebScoket with examples.

Write in the last

If you find this article helpful, please like it and share it with more people who need it!

Welcome to pay attention to [Quanzhendaolu] and wechat public account [Quanzhendaolu], to get more good articles and free books!
There is a need [Baidu] & [bytedance] & [JD] & [ape counselling] within the push, please leave a message oh, you will enjoy the VIP level extreme speed within the push service ~

Past oliver

Wechat JS API payment implementation

Create a personalized Github profile

The interviewer asks you<img>What elements do you say

Special JS floating point number storage and calculation

Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future

Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles

HTML Tabindex

A few lines of code to teach you to solve wechat poster and TWO-DIMENSIONAL code generation

Vue3.0 Responsive data principle: ES6 Proxy

Read on to make your interviewer fall in love with you

How to draw a fine line gracefully

Front-end performance optimization -HTML, CSS, JS parts

Front-end performance optimization – Page loading speed optimization

Front-end performance optimization – Network transport layer optimization