Webscoket

The main API

Const ws = new WebSocket (ws: / / 192.168.0.200: '8005') / / ws instance creation ws. The onopen () = = > {} / / connect the ws ws. The onerror = () = > {} / / receive an error message Ws. The onmessage () = = > {} / / receiving back-end data ws onclose () = = > {} / / close the wsCopy the code

use

xxx.vue

<template> <div> < button@click ="send"> </button> </div> </template> <script> export default {data () {return { Path: "ws: / / 192.168.0.200:8005 / qrCodePage/ID = 1 / refreshTime = 5", sockets: ""}}, mounted () {/ / initializes the enclosing the init ()}, methods: { init: Function () {if(typeof(WebSocket) === "undefined"){alert(" your browser does not support sockets ")}else{// Instantiate socket this.socket = new WebSocket(this.path) // Listen for socket connections this.socket.onopen = this.open // Listen for socket error messages this.socket. onError = this.error // This.socket. onMessage = this.getMessage}}, open: function () {console.log(" Socket connection succeeded ")}, error: Function () {console.log(" error ")}, getMessage: function (MSG) {console.log(MSG)}, send: function () { this.socket.send(params) }, close: Function () {console.log("socket closed ")}}, Destroyed () {this.socket.onclose = this.close}} </script> <style> </style>Copy the code

Frequently asked Questions

Symptom: If no message is sent for a long time, the message is automatically disconnected.

Solution: Keep the heartbeat connection: The heartbeat detection method is as follows: Sends a data to the server at regular intervals. After receiving the data, the server returns a data to the client. If the client onMessage event can listen for returned data, the connection is not broken. Otherwise, the connection is disconnected and the client needs to send a request again.

TimeoutObj = setInterval(() => {let date = new date ()) This.socket. send(' Send heartbeat to back end ${date} ')}, 2 * 60 * 1000)}Copy the code

Feel free to like and comment if you find it helpful. The views expressed above are personal. Please correct any errors. If you are interested in the front, welcome to my personal blog sundestiny. Making. IO/myblog /