vue简单的websocket组件封装

4 篇文章 0 订阅
<template>

</template>

<script>
import {
    getToken
} from "@/libs/util";

/**
 *  事件:onConnecting  正在连接事件
 *        onRealTimePush  实时消息事件
 *         onOpen 连接成功
 */
export default {
    name: "web-socket",
    data: function () {
        return {
            maxReconnect: 600,
            //当前已经尝试重连次数
            curReConnect: 0,
            reTime: 0,
            pollTime: 0,
            url: "",
            ws: {},
            cookie: "",
        };
    },
    created() {
        this.cookie = getToken();
    },
    mounted() {
        this.createObservableSocket(this.$config.websocketurl);
    },
    beforeDestroy() {
        this.stopPoll();
        this.close();
    },
    methods: {
        createObservableSocket: function (url) {
            this.url = url;
            this.createWebSocket();
        },
        close: function () {
            if (this.ws && this.ws.readyState == 1) {
                this.curReConnect = this.maxReconnect + 500;
                this.ws.close();
                delete this.ws;
            }
        },
        createWebSocket: function () {
            try {
                if (this.ws && this.ws.readyState == 1) {
                    return this.ws;
                }
                this.ws = new WebSocket(this.url);
                this.ws.onmessage = this.onMessage.bind(this);
                this.ws.onerror = (evetn) => {
                    console.log(evetn);
                };
                this.ws.onclose = this.reConnect.bind(this);
                this.ws.onopen = (evetn) => {
                    this.curReConnect = 0;
                    this.stopPoll();
                    this.heat();
                    this.poll();
                    this.$emit("onOpen");
                };
            } catch (err) {
                console.log(err);
            }
        },
        onMessage: function (event) {
            try {
                console.log("收到推送:" + event.data);
                let jsonObj = JSON.parse(event.data);
                console.log(jsonObj);
                this.preHandleMessage(jsonObj);
            } catch (err) {
                console.log(err);
            }
        },
        /**
         * 发送心跳
         * */
        heat: function () {
            setTimeout(
                function () {
                    try {
                        if (this.ws.readyState == 1) {
                            let jsonStr = JSON.stringify({
                                MsgType: 0,
                                Content: this.cookie,
                            });
                            this.ws.send(jsonStr);
                            console.log("ws心跳包:\t" + jsonStr);
                        } else if (this.ws.readyState == 3) {
                            this.curReConnect = 0;
                            this.reConnect();
                        }
                    } catch (err) {
                        console.log(err);
                    }
                }.bind(this),
                1000
            );
        },

        /**
         * 持续心跳
         * */
        poll: function () {
            this.pollTime = setInterval(
                function () {
                    this.heat();
                }.bind(this),
                50 * 1000
            );
        },
        stopPoll: function () {
            clearInterval(this.pollTime);
        },
        /**
         * 重连
         * */
        reConnect: function () {
            clearTimeout(this.reTime);
            if (this.curReConnect < this.maxReconnect) {
                try {
                    if (this.ws.readyState == 3) {
                        this.$emit("onConnecting");
                        this.createWebSocket();
                        this.curReConnect++;
                    }
                } catch (err) {
                    console.log(err);
                }
                this.reTime = setTimeout(
                    function () {
                        this.reConnect();
                    }.bind(this),
                    (this.curReConnect / 3 + 1) * 5000
                );
            } else {
                console.log("重连失败,已超过最大重连次数:" + this.maxReconnect);
            }
        },
        lowerCase(jsonObj) {
            for (var key in jsonObj) {
                jsonObj[key.substring(0, 1).toLowerCase() + key.substring(1)] =
                    jsonObj[key];
                delete jsonObj[key];
            }
        },
        toLowerCase(jsonObj) {
            if (Array.isArray(jsonObj)) {
                jsonObj.forEach((item) => {
                    this.lowerCase(item)
                })
                return jsonObj
            } else if (typeof (jsonObj) == 'object' && jsonObj != null) {
                this.lowerCase(jsonObj)
                return jsonObj

            } else {
                return jsonObj

            }
        },
        preHandleMessage: function (jsonObj) {
            var content = false;
            if (jsonObj.Content) {
                content = this.toLowerCase(jsonObj.Content);
            }

            switch (jsonObj.MsgType) {
                case 1: {
                    //Can链接状态
                    this.$emit("onCanChange", content);

                    break;
                }
                case 2: {
                    //链接状态

                    this.$emit("onPlcChange", content);

                    break;
                }
               
            }
        },
    },
};
</script>

用法直接在页面写

<webscoket
  @onCanChange="onCanChange"
  @onPlcChange="onPlcChange"
></webscoket>]

getToken方法

    export const getToken = (key) => {
    const token = Cookies.get(key || TOKEN_KEY)
    if (token) return token
    else return false}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值