In our work, we are most exposed to the HTTP protocol. In recent years, many H5 apis and technologies have sprung up and started to carry forward. Today we will discuss one of the more interesting APIS, WebSocket

First of all, before introducing the main characters, there is always a setup, so LET me give you a few words about the most common HTTP protocols to distinguish them

In a few words about HTTP

HTTP is the protocol used for request-response in client/server mode, in which a browser submits an HTTP request to a server and the server responds to the requested resources

The implication is that you can think of this pattern as a walkie-talkie, where one person is talking and the other person is listening

HTTP is half duplex communication

The characteristics of this half-duplex communication are:

  • Data flows unidirectional at the same time. The client requests data from the server -> unidirectional, and the server returns data to the client -> unidirectional
  • The server cannot actively push data to the client

That’s a brief overview of the HTTP protocol, so let’s jump right into today’s topic

Duplex communication

Before the advent of H5 Websocket, the three most common ways to implement this push technology were polling, long polling, and iframe streams, but they all had some drawbacks

As a result, in the continuous efforts of the great gods, webSocket is defined as a good API to improve the implementation of duplex communication better

WebSocket era has come, don’t miss it!!

WebSocket

WebSocket is implemented to establish a permanent connection between the client and the server, and both sides can send data at will

Of course, if you go further, you should know that it is an application-layer protocol, based on the TCP transport protocol, and reuse the HTTP handshake channel

Let’s take a look at the advantages of WebSocket

The advantage of WebSocket

  1. Support two-way communication, real-time stronger (you can do a QQ, wechat, old iron)
  2. Better binary support
  3. Less control overhead (fewer packet headers controlled by the protocol when the WS client and server exchange data after the connection is created)

So that’s enough nonsense, let’s go to the actual combat and test the results directly

Tap the WebSocket together

Let’s first write down the WebSocket for the front page, see the basic usage, code, don’t hesitate

// Create a WebSocket instance. // We want to connect to the WS protocol. // The corresponding port is the server set port 9999let ws = new WebSocket('ws://localhost:9999'); // OnOpen is triggered by the connection between the client and the serverfunction() {
    ws.send('Oh, good for you.'); }; Ws.onmessage = is triggered when the server sends a message to the clientfunction(res) { console.log(res); // The actual message data is res.data console.log(res.data); // The actual message data is res.data console.log(res.data); };Copy the code

Websocket: WebSocket: WebSocket: WebSocket: Websocket: Websocket: Websocket: Websocket: Websocket

So to get things done, let’s write the websocket receiving and sending message part over there in the background. Go ahead

Wait, before you wank, you need to install it

// The background ws package NPM I WS-S needs to be installedCopy the code

Here we use Node Express to simply build a background service, and the directory structure is very simple, as shown in the figure below

const express = require('express'); const app = express(); App.use (express.static(__dirname)); App.listen (3000); / / = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = / / create a const websocket service Server = require ('ws').Server; Const ws = new Server({port: 9999}); const ws = new Server({port: 9999}); // Listen to the connection between the server and client'connection'.function(socket) {// listen for messages from the client'message'.function(msg) { console.log(msg); // The server can also send a message to the client socket.send(' here is what the server says to you:${msg}`);
    });
});
Copy the code

This creates a backend service. After accessing localhost:3000, you can see the message in the console

The next step is that websocket is an H5 standard, and older browsers don’t support it very well, so the front end has to deal with compatibility issues

Because of this, there is another library in the world that is much more useful, and this is the famous socket.io

Let’s continue to learn about the king of full-duplex communication

socket.io

Let’s take a look at what’s special about socket. IO

The characteristics of the socket. IO

  • Ease of use: Encapsulated server and client, easy to use
  • Cross-platform: Cross-platform, allowing you to develop real-time applications on either the server or the client
  • Adaptive: The browser decides whether to use WebSocket, Ajax long polling, Iframe streams, etc., to choose the best approach. Even IE5.5 is supported

Well, after reading the features, go to……

Less routine, more sincerity, cut the crap, and just go over it from the beginning

Socket. IO installation

// Install in the local project NPM I socket. IO -sCopy the code

Start the service, write the server

Again, use node’s Express framework to build a service

// server.js file const express = require('express'); const app = express(); App.use (express.static(__dirname)); // create a server server using node's HTTP module const server = require('http').createServer(app); // WebSocket is dependent on HTTP for handshakes const IO = require('socket.io')(server); // Listen to the connection between the client and server'connection'.function(socket) {// send a message to the client socket.send('Blue and white Porcelain'); // Listen to the client to see if the message has been received successfully'message'.function(msg) { console.log(msg); // The message sent by the client socket.send('The sky is blue and waiting for rain, and I'm waiting for you.'); }); }); Server. Listen (3000);Copy the code

The server code has been written, now start to write the front end, roll up your sleeves and work hard!!

After the server runs, the client needs to refer to a dynamically generated file path. If the path is a fixed direct reference (/socket.io/socket.io.js)

// index.html file... Omit // reference to socket. IO js file <script SRC ="/socket.io/socket.io.js"></script>
<script>
    const socket = io('/'); // Listen for successful connection to the server event socket.on('connect', () => {
        console.log('Connection successful');
        socket.send('Jay Chou'); }); // Listen for messages from the server socket.on('message'Console. log(' messages received by the client:${msg}`); }); // Listen for server disconnection event socket.on('disconnect', () => {
        console.log('Connection disconnected successfully');
    });
</script>
Copy the code

IO can accept a URL parameter when creating a socket

  • The URL can be the full HTTP address of the socket service, for example: IO (‘http://localhost:3000’)
  • Or relative paths, such as: IO (‘/’)
  • If not specified, the default connection path is: IO ()

That’s the basic usage, there are other ways to partition namespaces, add rooms, and broadcast, but I would like to go on

But next, the socket. IO chat room is so taxing that the audience is getting tired of it

So the time for the wise man is coming, put it in the next period to give you, hard to watch, 886