What is the webSocket

WebSocket is a protocol for full duplex communication over a single TCP connection. It makes the data exchange between the client and the server easier, allowing the server to actively push data to the client.

In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

What problems WebSocket solves:

When not using WebSocket, if we need to establish a long connection, there are several methods:

  • polling
  • Long polling (common)
  • SSE(Server Send Event)

When there are scenarios such as sports events, chat rooms, real-time locations, and so on, the client can only get changes on the server side by polling (timed requests) to see if there are new changes on the server side. The emergence of WebSocket, so that the server side can actively send information to the server side, so that the browser has real-time two-way communication ability, this is WebSocket to solve the problem

  • Bandwidth issues: Websockets have smaller protocol headers than HTTP and are delivered on demand.
  • Data real-time issues: WebSocket can deliver data in real time with less latency compared to polling and long polling.
  • State issues: WebSocket can maintain a specific state after establishing a connection, as opposed to HTTP stateless requests.

WebSocket vs. HTTP

The basic use

The client

const ws = new WebSocket('ws://localhost:8888')

ws.onopen = (a)= > {
  console.log('WebSocket onopen')
}

ws.onmessage = e= > {
  console.log(e)
  console.log(e.data)
}

ws.onclose = e= > {
  console.log('WebSocket onclose')
}

ws.onerror = e= > {
  console.log('WebSocket onerror')}Copy the code
  • Websocket. onopen: called after the connection is successful
  • Websocket. onMessage: Called when a server message is received
  • Websocket. onclose: called after the connection is closed
  • Websocket. onerror: called after an error occurs

Server Example (KOA)

const Koa = require('koa')
const WebSocket = require('ws')

const app = new Koa()
const ws = new WebSocket.Server({ port: 8888 })

ws.on('connection', ws => {
  console.log('server connection')

  ws.on('message', msg => {
    console.log('server receive MSG: ', msg)
  })

  ws.send('Information from the server')
})

app.listen(3000)
Copy the code

WebSocket can pass String, ArrayBuffer, and Blob data types, so it can be any one of them when receiving a message. Of these, String and ArrayBuffer are used the most.

  • If it is a String, it can be converted directly to a String handler, such as JSON.
  • If it is a binary BLOB type, you need to use ArrayBuffer and DataView to process it, as described below.

Binary data includes blob objects and Arraybuffer objects, so we need to treat them separately.

// Receive data
ws.onmessage = function(event) {
  if (event.data instanceof ArrayBuffer) {
    // Determine the ArrayBuffer object
  }
  if (event.data instanceof Blob) {
    // Determine the Blob object}}// Send an example of Blob objects
let file = document.querySelector('input[type="file"]').files[0]
ws.send(file)
// Send an example of an ArrayBuffer object
var img = canvas_context.getImageData(0.0.400.320)
var binary = new Uint8Array(img.data.length)
for (var i = 0; i < img.data.length; i++) {
  binary[i] = img.data[i]
}
ws.send(binary.buffer)
Copy the code

The websocket. bufferedAmount property, which indicates how many bytes of binary data are not sent if the sent binary is large

var data = new ArrayBuffer(10000000)
socket.send(data)
if (socket.bufferedAmount === 0) {
  // Send complete
} else {
  // Send is not finished yet
}
Copy the code

Summarize the advantages of WebSocket

  • Two-way communication (first and most important).
  • The data format is relatively light, with low performance overhead and high communication efficiency
  • Protocol-controlled packets have smaller headers, whereas HTTP requires complete headers for each communication
  • Better binary support
  • There are no same-origin restrictions, and clients can communicate with any server
  • It has good compatibility with HTTP protocol. The default ports are also 80 and 443, and the handshake phase uses HTTP protocol, so it is not easy to mask the handshake and can pass various HTTP proxy servers