vue+websocket demo 实例

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>

 

转载于:https://www.cnblogs.com/mengfangui/p/11320270.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值