首页 > Web开发 > 详细

vue+websocket demo 实例

时间:2019-08-08 13:34:11      阅读:202      评论:0      收藏:0      [点我收藏+]

vue+websocket demo:

<!-- vue + websocket连接demo -->
<template>
    <div class="">vue + websocket连接demo</div>
</template>

<script>
export default {
    data() {
        return {
            // 连接标志位
            lockReconnect: false,
            wsCfg: {
                // websocket地址
                url: ‘ws://10.74.52.107:9001/websocket‘
            }
        };
    },
    methods: {
        createWebSocket() {
            try {
                // 创建Web Socket 连接
                const socket = new WebSocket(this.wsCfg.url);
                // 初始化事件
                this.initEventHandle(socket);
            } catch (e) {
                // 出错时重新连接
                this.reconnect(this.wsCfg.url);
            }
        },
        initEventHandle(socket) {
            // 连接关闭时触发
            socket.onclose = () => {
                console.log(‘连接关闭‘);
            };
            // 通信发生错误时触发
            socket.onerror = () => {
                // 重新创建长连接
                this.reconnect();
            };
            // 连接建立时触发
            socket.onopen = () => {
                console.log(‘连接成功‘);
            };
            // 客户端接收服务端数据时触发
            socket.onmessage = msg => {
                // 业务逻辑处理
                this.list = msg.data;
            };
        },
        reconnect() {
            if (this.lockReconnect) {
                return;
            }
            this.lockReconnect = true;

            // 没连接上会一直重连,设置延迟避免请求过多
            setTimeout(() => {
                this.lockReconnect = false;
                this.createWebSocket(this.wsCfg.url);
            }, 2000);
        }
    },
    mounted() {
        this.createWebSocket();
    }
};
</script>

 

vue+websocket demo 实例

原文:https://www.cnblogs.com/mengfangui/p/11320270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!