Writing in the front

Cut the crap. Old rules. Start with past lives

What is the webSocket

WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5. WebSocket makes it easier to exchange data between the client and the server, 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 establish a persistent connection and two-way data transfer.

Listen to the official explanation, you are not like reading classical Chinese, we give him a popular explanation

WebSocket is a network communication protocol that enables the server to actively push data to the client

To put it bluntly, he can actively push data to the client. Then we have a question: why do we need him?

Why webSocket

If we don’t have HTTP as a universal protocol, why do we need it? HTTP/2 doesn’t do server push. HTTP/2 can only push static resources, not even information. What does that mean? After much exploration, it was found that HTTP/2’s so-called server push is actually a server that can respond to multiple resources when it receives a request.

For example, when I request A.HTML from the server, the server not only gives it to us, but also throws js, CSS and other files at us. The most obvious benefit is that the browser saves page load time by not having to parse the page and then make a request to retrieve the data. So HTTP/2 is not an alternative to webSocket, and certainly not if we are going to implement instant messaging

How to use the webSocket

Before we know how to use webSocket, let’s look at how it works. Okay

The principle of

If you want to use webSocket to establish a link with the server, you first need to establish a TCP link, and then use HTTP/1.1 protocol in the handshake phase. In fact, I think he borrows part of HTTP protocol to achieve his ability

Now let’s see how he does it.

// Request message GET WSS ://webchat-bj-test5.clink. Cn&province = HTTP/1.1 // request address Host: webchat-bj-test5.clink. Upgrade Pragma: no-cache cache-control: no-cache user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.9 Safari/537.36 // UA Upgrade: Websocket / / the following is the websocket these things Origin: http://clink2.clink.cn:5050 Sec - websocket - Version: 13 Accept - Encoding: gzip, deflate, br Accept-Language: zh-CN,zh; Q =0.9 sec-websocket-key: O5GLCYKZVQi2jTLENobvtg== sec-websocket-extensions: permessage-deflate; client_max_window_bitsCopy the code
Date: Mon, 30 Mar 2020 09:21:00 GMT Connection: Nginx /1.13.9 Server: nginx/1.13.9 Upgrade Vary: Origin Vary: access-control-request-method Access-Control-Request-Headers Access-Control-Allow-Origin: * Access-Control-Allow-Credentials:trueSec-websocket-accept: uZpmP+PDDvSeKsEg9vkAsWcqPzE= sec-websocket-extensions permessage-deflate; client_max_window_bits=15Copy the code

The above two code you will find, he is on the basis of HTTP added something, tell the server, I am a Websocket request server to do the parsing and processing after solid communication!

It is time to introduce the request and corresponding messages

  • 1. The protocol identifier is WS (or WSS if encrypted) and the server URL is the URL
  • Sec-websocket-key is a Base64 encode value, which is randomly generated by the browser and used to verify that the server is compatible
  • Sec — websocket-protocol is a list of client request subprotocols, in order of preference
  • Sec-websocket-version is the WebSocket Draft (protocol Version) that tells the server to use.
  • 5. Upgrade tells the client that we have successfully switched to the WebSocket protocol
  • Sec-websocket-accept: sec-websocket-accept: sec-websocket-accept: sec-websocket-accept: sec-websocket-accept: sec-websocket-accept

This then creates a Websocket link

How to use

Usage aspect is quite simple, we can operate according to MDN

Var ws = new websocket ("wss://webchat-bj-test5.clink.cn"); // The onopen property of the instance object, which specifies the callback function if the connection is successful. ws.onopen =function(evt) { 
  console.log("Connection open ..."); // The send() method of the instance object is used to send data to the server. ws.send("Hello WebSockets!"); }; // The onMessage property of the instance object, which specifies the callback function to receive server data. ws.onmessage =function(evt) {
  console.log( "Received Message: "+ evt.data); ws.close(); }; // The onclose property of the instance object, which specifies the callback function after the connection is closed. ws.onclose =function(evt) {
  console.log("Connection closed.");
};     
Copy the code

Ruan yifeng’s example above basically covers common usage scenarios. If you are curious, please ask MDN for answers

Of course, the native stuff is pretty hard to use because the back end processors aren’t that handy when you set up a link, so this is where the awesome library comes in. Again, I recommend socketIO

SocketIO

SocketIO encapsulates Websockets, AJAX, and other communication methods into a unified interface, which means that when you use SocketIO, you don’t have to worry about compatibility and the underlying layer automatically selects the best communication method. Therefore, WebSocket is a subset of SocketIO.

Cut to the code

Var app = require('koa') (); Var server = require('http').createServer(app.callback()); Var IO = require('socket.io')(server); IO. On ('connection'.function(socket){// IO. Emit for broadcast, socket.emit for private socket.on('eventB'.function(socket){ /* */ });

socket.emit('eventA'/ * * /); }); server.listen(3000);Copy the code
// front-end <script SRC ="http://localhost:3000/socket.io/socket.io.js"></script> <script> // create a service var socket = new IO ()'eventA'.function (res) {
        console.log('User 1 has received a message')
    })
    socket.emit('eventB', data)
</script>
Copy the code

At this point, the framework implements the complete even message

compatibility

Websocket features (key: interview to test)

  • 1, based on THE TCP protocol, the implementation of the server side is relatively easy.
  • 2, with HTTP protocol has good compatibility. 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.
  • 3, data format is relatively light, low performance overhead, efficient communication.
  • 4. You can send text or binary data.
  • 5, there is no source restriction, the client can communicate with any server.

Current Web im solutions

Ajax polling

Ajax polling is simple enough that the browser sends a request every few seconds to ask if the server has any new messages. This access, which is very back-end friendly and can call the interface indefinitely, has the fatal disadvantage of wasting bandwidth and server resources. Small apps can survive, but what if thousands of people want instant messaging? That’s not enough

2. Long poll

In fact, the principle is similar to ajax polling, which adopts polling mode, but adopts blocking model (always call, do not hang up if you have not received), that is, after the client initiates a connection, if there is no message, it does not return a Response to the client. It does not return until there is a message, after which the client establishes the connection again and the cycle starts again. This solves the problem of the infinite call interface, but maintains a long link that keeps an HTTP request in pedding state! Server stress is also quite high, so, still not desirable

3, websocket

That’s our hero today. Doesn’t he have any flaws?

Yes, of course, companies will have to spend more money because of the secondary parsing required to transfer data, which increases development costs and difficulty

SSE

Some students mentioned SSE in the comments, let’s explore it

Sever-Sent Event (SSE) means that the browser sends an HTTP request to the server to maintain a long connection. The server continuously pushes “message” to the browser in one direction to save network resources and avoid sending requests and establishing new connections all the time.

If you look at the concept, it’s basically like a long poll, and it has a browser built in EventSource object to operate on

// create a link varsource= new EventSource(); // Close the link source.close();Copy the code

The advantages and disadvantages

The advantage, of course, is that it is an HTTP request, and because it is wrapped in the browser, it is easy to use, saving development costs

The disadvantages are also quite obvious, not being able to implement two-way messaging

Afterword.

First of all, thank you for your article

WebSocket tutorial talk about instant messaging on the Web

Due to the work needs, learning websocket, and sorting again, to help everyone a article all done, don’t thank me, please call me Lei Feng!