龙空技术网

vue websocket 连接 断线重连

Web初学者 1777

前言:

此刻咱们对“js websocket断线重连”大概比较注意,咱们都想要知道一些“js websocket断线重连”的相关资讯。那么小编也在网上收集了一些对于“js websocket断线重连””的相关文章,希望兄弟们能喜欢,兄弟们一起来学习一下吧!

src\utils\webSocket.js

class Socket {    /**     * @description: 初始化实例属性,保存参数     *      */    constructor(options) {        this.url = options.url;        this.callback = options.received;        this.name = options.name || 'default';        this.ws = null;        this.status = null;        this.pingInterval = null;        // 心跳检测频率        this._timeout = 3000;        this.isHeart = options.isHeart;        this.isReconnection = options.isReconnection;    }    connect(data) {        this.ws = new WebSocket(this.url);        // 建立连接        this.ws.onopen = (e) => {            this.status = 'open';            console.log("连接成功", e)            if (this.isHeart) {                // 心跳                this._heartCheck()            }            // 给后台发送数据            if (data !== undefined) {                return this.ws.send(JSON.stringify({                    type: 'init'                }))            }        }        // 接受服务器返回的信息        this.ws.onmessage = (e) => {            if (typeof this.callback === 'function') {                return this.callback(e.data)            } else {                console.log('参数的类型必须为函数')            }        }        // 关闭连接        this.ws.onclose = (e) => {            console.log('onclose', e)            this._closeSocket(e)        }        // 报错        this.onerror = (e) => {            console.log('onerror', e)            this._closeSocket(e)        }    }    sendMsg(data) {        let msg = JSON.stringify(data)        return this.ws.send(msg)    }    _resetHeart() {        clearInterval(this.pingInterval)        return this    }    _heartCheck() {        this.pingInterval = setInterval(() => {            if (this.ws.readyState === 1) {                this.ws.send(JSON.stringify({                    type: 'ping'                }))            }        }, this._timeout)    }    _closeSocket(e) {        this._resetHeart()        if (this.status !== 'close') {            console.log('断开,重连', e)            if (this.isReconnection) {                // 重连                this.connect()            }        } else {            // 手动关闭了            console.log('手动关闭', e)        }    }    close() {        this.status = 'close'        this._resetHeart()        return this.ws.close();    }}export {    Socket}

src\mixin\webSocket.js

import {    Socket} from "../utils/webSocket";export default {    data() {        return {            ws: {},        };    },    components: {},    watch: {},    computed: {},    destroyed() {        // 手动关闭        this.ws.close()    },    mounted() {},    methods: {        initWebSocket(obj) {            this.ws = new Socket({                url: obj.url, // 地址                name: "", // name                isHeart: true, // 是否心跳                isReconnection: true, //是否断开重连                received: (data) => {                    // 监听服务器返回信息                    //if (data == '连接成功') {                    //   return false                    //}                    // console.log("received 监听服务器返回信息", data,JSON.parse(data));                  // 处理数据 给需要用到的页面watch                },            });            // 建立连接            // let data = {            //     type: "init",            // };            this.ws.connect();            // 发送消息            // let sendData = {            //     type: "sendMsg",            // };            // this.ws.sendMsg(sendData);        },        getParams(url) {            var temp1 = url.split('?');            var pram = temp1[1];            var keyValue = pram.split('&');            var obj = {};            for (var i = 0; i < keyValue.length; i++) {                var item = keyValue[i].split('=');                var key = item[0];                var value = item[1];                obj[key] = value;            }            return obj        }    }};

view

import webSocketMixin from "../../mixin/webSocket";  mixins: [webSocketMixin],      watch: {  		// 接收监听推送的数据  }  mounted() {    // 连接websocket    this.initWebSocket({ wsurl: 'ws:地址'});  },

标签: #js websocket断线重连 #socket断线重连机制 #socket连接中断 #socket断线重连 #websocket断开重连