在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

你可能感兴趣的:(web)