在vue.js上使用websocket

在vue.js上使用websocket有两种方法:
方法一:使用内置websocket实现

data() {
    return {
        websock: null,
    }
},

mounted() {
    //初始化
    this.initWebSocket();
},

methods() {
    initWebSocket(){ //初始化weosocket
        const wsuri = this.config.ws_server;
        //连接服务端
        this.websock = new WebSocket(wsuri);
        //指定事件回调
        this.websock.onmessage = this.websocketOnMessage;
        this.websock.onopen = this.websocketOnOpen;
        this.websock.onerror = this.websocketOnError;
        this.websock.onclose = this.websocketClose;
        },

        websocketOnOpen(){ //连接建立之后执行send方法发送数据
            let actions = {'type': 100, 'msg': 'requestPermission'}
            this.websocketSend(JSON.stringify(actions));
            //连接后,定时发送,否则不段时间不通信会自动断连(时间长短一般是服务端指定的)
            var that = this;
            setInterval(function () {
                that.websocketSend(JSON.stringify({'type': 0, 'msg': 'ping'}));
            }, 15000);
        },

        websocketOnError(){//连接建立失败重连
            this.initWebSocket();
        },

        websocketOnMessage(e){ //数据接收
            const redata = JSON.parse(e.data);
            // eslint-disable-next-line
            console.log(redata);
            // eslint-disable-next-line
        },

        websocketSend(Data){//数据发送
                this.websock.send(Data);
        },

        // eslint-disable-next-line
        websocketClose(e){  //关闭
            // eslint-disable-next-line
            console.log('断开连接',e);
        },
}

方法二:使用socket.io实现
先安装socket.io

npm install vue-socket.io --save

示例:

import VueSocketio from 'vue-socket.io';
//连接websocket服务端,这句要在这里执行,放在mounted再执行有问题
Vue.use(VueSocketio, 'http://localhost');

export default {
    //......
    sockets:{
        //connection事件回调
        connect: function() {
            //eslint-disable-next-line
            console.log('connect');
        },
        //redirect事件回调 
        rediect: function() {
        }
    },
    
    methods: {
        send(data) {
            //发送data到emit_method事件
            this.$socket.emit('emit_method', data);
        }
    }
}

socket.io使用上还是要比传统的方法方便,省去要自己维护心跳和回调事件的实现
代码参考:Enlarge-Web

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值