WebSocket is an application layer protocol based on TCP for full duplex communication

As we know, HTTP protocol is a request/response mode, the server can not actively push data to the client

In order to implement the push function, Ajax polling is generally used, but such frequent requests will bring great pressure to the server

The WebSocket protocol is designed to solve this similar scenario by allowing the server to actively push data to the client

With a handshake, the browser and the server can create a persistent connection between the two, transmitting data in both directions until either side shuts it down

Currently, the sha-based handshake protocol is the most widely used. The detailed process is as follows:

  • The browser makes an HTTP request to the server, but this request is different from a normal request in that it attaches some header information
  • The server parses the header information and returns a response, which establishes the WebSocket connection

A typical client request is as follows:

GET ws://localhost:5000 HTTP/1.1 Host: localhost Origin: http://localhost:5000 Upgrade: websocket Connection: Upgrade SEC-websocket-key: random string sec-websocket-version: 13Copy the code
  • Connection: Must be set toUpgradeIndicates that the client wishes to upgrade the protocol
  • Upgrade: Must be set towebsocketIndicates that you want to upgrade the protocol to Websocket
  • Sec-WebSocket-Key: random string, with response inSec-WebSocket-AcceptIs used for comparison verification

A typical server response would look like this:

HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade SEC-websocket-accept: Sec-websocket-location: ws://localhost:5000Copy the code
  • Connection: If the value isUpgrade“Indicates that the server agrees to the upgrade protocol
  • Upgrade: If the value iswebsocketIndicates that you agree to upgrade the protocol to Websocket
  • Sec-WebSocket-Accept: Confirmed and encrypted by the serverSec-WebSocket-Key

Now that we understand the principle, let’s look at how to use WebSocket

In the client browser, you can create an object through the constructor WebSocket()

The url parameter is used to specify the connection address, and the protocol parameter is used to specify acceptable subprotocols

WebSocket(url, [protocol])
Copy the code

The constructor returns a WebSocket object with the following common properties and methods:

  • ReadyState: read-only property, indicating connection status

    0 indicates that the connection is not established, and 1 indicates that the connection is established and can be communicated with

    2 indicates that the connection is being closed, and 3 indicates that the connection is closed or cannot be opened

  • BufferedAmount: Read-only property, number of bytes waiting to be transferred in the cache

  • Onopen: Specifies the listener function for the open event, which is triggered when a connection is established

  • Onmessage: Specifies the listener function for the message event, which is fired when data is received

  • Onerror: Specifies a function that listens for error events and is fired when an error occurs

  • Onclose: Specifies a listener for the close event that is fired when the connection is closed

  • Send () : sends data

  • Close () : closes the connection

var ws = new WebSocket('ws://localhost:5000')

ws.onopen = function(event) { 
    console.log('open')
}

ws.onmessage = function(event) {
    console.log('message', event.data)
    ws.send('Goodbye')
    ws.close()
}

ws.onclose = function(event) {
	console.log('close')}; ws.onerror =function(event) {
	console.log('error')}Copy the code

For the server, WebSocket is just a protocol, different languages and different frameworks will have different implementation

Let’s write a simple Demo using Node.js as an example

var express = require('express')
var expressWs = require('express-ws')

var app = express()

expressWs(app)

app.ws('/'.function (ws, req){
    // ws: WebSocket instance
    // req: Request instance
    ws.send('Hello')
    ws.on('message'.function (msg) {
        console.log(msg)
    })
})

var server = app.listen(5000.'127.0.0.1'.function() {
    console.log('server running at http://127.0.0.1:5000)})Copy the code