preface

WebSocket many people have heard of, have not seen, have not used, think is a very lofty technology, in fact, this technology is not mysterious, can be said to be a very easy to master the technology, I hope after reading this article, immediately put out the chestnut in the article to try their own, practice out of real knowledge.

Origin of WebSocket 🤞

We usually in the development process, contact is HTTP protocol, under normal circumstances, we send HTTP requests to the server through the client, the server responds to request resources, this process we can not be more familiar with.

However, HTTP protocol has a problem that communication can only be initiated by the client, that is, HTTP protocol is one-way communication.

For chestnut, we customize a shares in the stock, we are very concerned about when it is higher than the price of the ready to sell, we can’t always staring at the share price, this time just think, if the price of the stock exchange can automatically push the much good, if the servers are less than normal HTTP protocol we do take the initiative to push the message to the client.

Of course the chestnuts also can work it out, we can use the polling, namely every once in a while, a client like server launched an inquiry, but the biggest problem of polling is very inefficient, and it’s such a waste of resources, for tens of thousands of Chinese chives, are focusing on the stock, all in a request, that the request quantity is very big, therefore, in the efforts of many bosses, WebSocket was born!

Advantages of WebSocket 😊

The advantages of WebSocket can be seen from the above mentioned stock chestnuts:

  1. Support two-way communication, better real-time
  2. Better and lighter communication with the server because WebSocket provides a simple message specification that ADAPTS to long connections more quickly
  3. Support for extensions. The WS protocol defines extensions, and users can extend the protocol or implement custom sub-protocols that can be encrypted
  4. You can send text or binary data
  5. There is no same-origin policy, clients can connect to any server (without same-origin policy, we can also solve cross-domain problems 🤣)

WebSocket application 🙈

Now WebSocket uses many, the most typical have the following

  1. The chat room
  2. Website video bullet screen
  3. Real-time display of stock prices
  4. Internet of Things data push

There are other scenarios that you can think about

For example, 🌰

Having said so much, we can implement a WebSocket by ourselves, examples include WebSocket server, WebSocket client (web page). The full code can be found here, if you can help, click ⭐️.

We mentioned above that WebSocket technology can be applied to real-time display of stock prices, so let’s take an example.

The first effect

In effect, we can see that when we click start, the client can request the server, and the server can push the real-time stock price.

All right, look at the results and we’ll pull out the specific code

1. The client

For convenience, Vue and ElementUi are used. The code can be seen here.

    / / webscoekt connection
    vm.ws = new WebSocket('ws://localhost:8082')
    / / open the websocket
    vm.ws.onopen = function (e) {
      console.log('Connection to server opened')
      // Send a message
      const stockName = vm.ws.send(
        JSON.stringify(
          vm.stockData.map((i) = > {
            return i.name
          })
        )
      )
      console.log('sened a mesg')}// The server returned a message
    vm.ws.onmessage = function (e) {
      / / analytical data
      vm.stockData = JSON.parse(e.data)
    }
Copy the code

2. The service side

The server uses the WS library. You can also use socket. IO

First, install the library

// Install the WS library
npm  i ws 
Copy the code

Let’s start with server.js

const WebSocket = require('ws')

// Generate the WebSocket server
const wss = new WebSocket.Server({ port: 8082 })

function randomInterval(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min) / 100
}

/ / connection
wss.on('connection'.function (ws) {
  // Receive information
  ws.on('message'.function (message) {
    stockRequest = JSON.parse(message)
    console.log('Received message', stockRequest)
  })

  // Simulate stock price
  const clientStockUpdater = setInterval(function () {
    for (let i in stockRequest) {
      stockRequest[i].price += randomInterval(- 100..100)
      // Push a message
      ws.send(JSON.stringify(stockRequest))
    }
  }, 1000)

  / / close the websocket
  ws.on('close'.function () {
    clearInterval(clientStockUpdater)
  })
})

Copy the code

Conclusion ✍ ️

After looking at the above is not found WebSocket is very simple, in fact, this article is just a WebSocket introductory tutorial, we might as well start to write their own, in my example in deepening, explore the encryption of WebSocket and heartbeat mechanism.