[Basics] Why WebSocket?

The most common interaction mode between the front end and the back end is that the front end sends the data request, and the back end responds to the data transmission before the end shows it. If the front end does not perform operations, the back end cannot actively push data to the front end. Therefore, in business scenarios where the server is required to actively push messages to the client and the client can also actively send messages to the server, WebSocket comes into play.

【 Features 】 The features of WebSocket are as follows:

(1) Based on THE TCP protocol, the implementation of the server side is relatively easy.

(2) It has good compatibility with HTTP protocol. 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) The data format is relatively light, the performance overhead is small, and the communication is efficient.

(4) Can send text, can also send binary data.

(5) There is no source restriction, and the client can communicate with any server.

(6) The protocol identifier is WS (if encrypted, WSS), and the server URL is the URL.

Note the following points when using WebSocket in Vue:

(1) The current browser is compatible with WebSocket as follows: Compatibility

(2) Connect to WebSocket when component is loaded and disconnect WebSocket when component is destroyed

(3) The socket module must be introduced to the back-end interface; otherwise, the connection cannot be realized.

1. The basic version

1.0 Basic introduction to native WebSocket

The event
open Socket.onopen Triggered when the connection is established
message Socket.onmessage Triggered when the client receives data from the server
error Socket.onerror Triggered when a communication error occurs
methods
Socket.send() Use the connection to send data
Socket.close() Close the connection
attribute
ReadyState Read-only property Indicates connection status
BufferedAmount Read-only property The number of UTF-8 text bytes that have been put into a queue by Send () for transmission, but have not yet been sent

1.1 Code Analysis (Current version includes heartbeat mechanism)

<script> export default {components: {VueQr}, data() {return {lockReconnect: false, ServerTimeoutObj: null, // Heartbeat countdown timeoutNum: null, // Disconnect reconnection countdown}; }, created() { this.initWebSocket(); }, destroyed() { this.websock.close(); Methods: {currentTime() {setInterval(this.formatdate, 500); }, initWebSocket() {// initialize weosocket const wsuri = "WSS :// XXXXXXX /xx/xx/" + this.roomid; this.websock = new WebSocket(wsuri); This.websock. onMessage = this.websocketonMessage; Onopen = this.websocketonOpen; // This. Websock. onError = this. Websocketonerror; This.websocket. onclose = this.websocketClose; }, // trigger webSocketonOpen () {// start heartbeat this.start(); / / connection is established executed after the send method to send data / / let the actions = {" room ":" 007854 ce7b93476487c7ca8826d17eba ", "info", "1121212"}; // this.websocketsend(JSON.stringify(actions)); }, // Raise webSocketonError () {console.log(" error "); this.reconnect(); }, // When the client receives server data, the webSocketonMessage (e) {console.log(e.ata); // Heartbeat resets this.reset(); }, webSocketSend (Data) {// Data is sent this.websocket.send (Data); }, // Trigger webSocketClose (e) when the connection is closed {// close console.log(" disconnect ", e); / / reconnection enclosing the reconnect (); }, reconnect() {var that = this; if (that.lockReconnect) { return; } that.lockReconnect = true; Timeoutnum && clearTimeout(that.timeoutnum); Thate.timeoutnum = setTimeout(function () {// new connection thate.initwebSocket (); that.lockReconnect = false; }, 5000); }, reset() {var that = this; // Clear time clearTimeout(that.timeoutobj); clearTimeout(that.serverTimeoutObj); // Restart the heartbeat thate.start (); }, start() {// Start heartbeat console.log(" start heartbeat "); var self = this; self.timeoutObj && clearTimeout(self.timeoutObj); self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj); Self.timeoutobj = setTimeout(function () {// If (self.ws. ReadyState == 1) {// Self.ws. Send ("heartCheck"); } else {// otherwise reconnect(); } self.serveroutobj = setTimeout(function () {self.ws.close(); }, self.timeout); }, self.timeout); }, }, mounted() { this.currentTime(); }, // Destroy timer beforeDestroy() {if (this.formatDate) {clearInterval(this.formatdate); // Clear timer}},} before Vue instance is destroyed; </script>Copy the code