有学有练才叫学习:学而不思则罔,思而不学则殆:学而不习,纸上谈兵,习而不进,画地为牢!

websocket断开连接(vue websocket 连接 断线重连)

vue 炮渣日记 2周前 (11-13) 16次浏览 已收录 0个评论 扫描二维码

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:地址'});
  },
喜欢 (0)
炮渣日记
关于作者:
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址