First, know WebSocket
HTML5 is an application layer protocol that provides full-duplex communication between a browser and a server. It is based on the TCP transport protocol and multiplexes the HTTP handshake channel. WebSocket is a network transport protocol that can carry out full-duplex communication over a single TCP connection and is located at the application layer of the OSI model. WebSocket is a persistent protocol, as opposed to NON-persistent HTTP.
For most Web front-end developers, there are just a few things to keep in mind:
- WebSocket can be used in a browser
- Support for two-way communication
- Very simple to use
1. What are the advantages
The comparison here is the HTTP protocol, which, in a nutshell, supports two-way communication, is more flexible, more efficient, and more scalable.
- Support two-way communication, more real-time.
- Better binary support.
- Less control overhead. After the connection is created, the packet header controlled by the protocol is small when the WS client and server exchange data. Without headers, the server to client header is only 2 to 10 bytes (depending on the packet length). Client to server requires an additional 4 bytes mask. HTTP, on the other hand, requires a full header for every communication.
- Support for extensions. The WS protocol defines extensions. Users can extend the protocol or implement custom subprotocols. (such as support for custom compression algorithms, etc.)
- The protocol identifier is
ws
(If encryption is used, the value iswss
), the server URL is the URL.
2. What do you need to learn
The most important is often the connection building process and data exchange tutorial. Of course, the format of the data is inescapable because it directly determines the capability of the protocol itself. A good data format makes the protocol more efficient and extensible.
Here’s a reference:
How to use Websocket
For web front-end developers, using WebSocket is actually quite simple, because WebSocket itself is a broadcast-listen model (also known as a publish-subscribe model), and front-end developers only need to connect, listen, and operate. You can experience a series of WebSocket processes
1. Establish the connection
Var ws = new WebSocket("ws:// your domain name or IP "); ws.onopen = function(evt) { console.log("Connection open ..." ); ws.send("Hello WebSockets!" ); }; ws.onmessage = function(evt) { console.log( "Received Message: " + evt.data); ws.close(); }; ws.onclose = function(evt) { console.log("Connection closed."); };Copy the code
The WebSocket object acts as a constructor to create a New WebSocket instance. After executing the above code, the client connects to the server. We’ll get a WS instance that has a lot of properties in it, but I’m just going to pick the ones that are usually used
2,ws.readyState
Property returns the current state of the instance object.
CONNECTING: If the value is 0, the connection is being started. OPEN: The value is 1, indicating that the connection is successful and communication is possible. CLOSING: If the value is 2, the connection is being closed. CLOSED: If the value is 3, the connection is CLOSED or the connection fails to be opened.Copy the code
We can determine the connection status of the socket by listening for WS-ReadyState.
3,ws.onopen
Instance objectonopen
Property to specify a callback function after a successful connection.
If the connection succeeds after the callback function
```js ws.onopen = function () { ws.send('Hello Server! '); } ` ` `Copy the code
4,ws.onclose
Instance object.onclose
Property for the callback function after the connection is closed.
ws.onclose = function(event) {
// handle close event Indicates the operations that the client needs to perform after the connection is closed
};
Copy the code
5,ws.onmessage
Instance object.onmessage
Property for a callback function after receiving data from the server.
ws.onmessage = function(event) {
var data = event.data;
// Process the data
};
Copy the code
6.ws.send
Method is used to send data to the server.
You need to negotiate with the backend to define the specific format of sending, such as sending plain text:
ws.send('your message');
Copy the code
7,ws.onerror
Callback function used when a connection error occurs.
Usually the connection is wrong, we just need to perform reconnect.
ws.onerror = function(event) {
// handle error event
};
Copy the code
Third, the problems encountered in the connection with webSocket
-
Based on the network security protocol conditions, HTTPS different source socket connection needs to use WSS ://+ domain name mode, the back end must use port 443 (and does not start any other security port) also needs to listen to the reverse proxy and pass all WSS traffic to the target WebSocket server
-
WSS connects to the socket server to avoid resource waste. If no operation is performed for a long time (or the timeout period set by NGINx), the socket will disconnect the connection. In this case, we need to perform heartbeat detection and periodically send heartbeat packets to the back end
Example:
var heartCheck = { timer: 0._obj : null._callback:null.init: function(wsObj, callback) { console.log("init"); this._obj = wsObj; callback && (this._callback = callback); this.sayHi(); }, sayHi: function() { clearTimeout(this.timer); this.timer = setTimeout(() = > { this.onError(); }, 10000); // If the connection is successful, send a heartbeat packet and start a delay. If there is no response beyond the value set by the delay, execute the onError method this._obj.send("hi," + this.timer); console.log("sayHi:" + this.timer); }, clear: function(flag) { // Clear the last delay and send the heartbeat packet again. If the flag is true, disconnect console.log("clear:" + this.timer); clearTimeout(this.timer); if(true === flag){ console.log("heartCheck finished"); return; } setTimeout(() = >{ this.sayHi(); }, 3000); }, onError: function() { console.log("onError:".this.timer); clearTimeout(this.timer); this._callback && this._callback(); }};//let hc = new heartCheck(); let uri = "ws://localhost:8080"; var ws = new WebSocket(uri); ws.onopen = (event) = > { console.log('ws onopen', event); ws.send('from client: hello'); heartCheck.init(ws); }; ws.onmessage = (event) = > { console.log('ws onmessage'); console.log('from server: ', event); showLog(event.data); heartCheck.clear(); }; ws.onclose = (event) = > { console.log("ws close", event); console.log(ws); heartCheck.clear(true); }; ws.onerror = (event) = > { console.log("ws error", event); console.log(ws); }; Copy the code
-
HTTPS cannot request HTTP
If an HTTP resource is loaded in an HTTPS address, the browser will consider it to be an unsafe resource and will block it by default. This will cause you to have incomplete resources, such as images that cannot be displayed, styles that cannot be loaded, JS that cannot be loaded. Because the style class, basically are written in the local, so generally ok, but some public JS files, often exists in CDN or other servers, at this time, if not access, may lead to the operation of the business is not completely. For example, if the jquery template fails to load, all actions and requests will be invalid.