vue使用websocket

167 阅读1分钟
<template>
    <div></div>
</template>
<script>
export default{
    data(){
        return{
            socketUrl:"",//ws地址
            socket:null,
            pingTimer:null
        }
    },
    mounted(){
        this.init_websocket();
    },
    methods:{
        init_websocket(){
            try{
                if('WebSocket' in window){
                    this.socket = new Websocket(this.socketUrl);
                }else{
                    console.log('您的浏览器不支持websocket');
                }
                this.socket.onopen = this.websocketonopen;
                this.socket.onerror = this.websocketonerror;
                this.socket.onmessage = this.websocketonmessage;
                this.socket.onclose = this.websocketonclose;
            }catch(e){
                this.reconnect();
            }
        },
        //重连
        reconnect(){
            console.log('尝试重连');
            setTimeout(()=>{
                this.init_websocket();
            },1 * 1000);
        },
        //连接websocket
        websocketonopen(){
            this.login_websocket();
        },
        websocketonerror(e){
            clearInterval(this.pingTimer);
            console.log('error',e);
            this.reconnect();
        },
        websocketonmessage(e){
            let data = JSON.parse(e.data);
            console.log('得到响应',data);
        },
        websocketonclose(){
            clearInterval(this.pingTimer);
            this.reconnect();
        },
        //每隔50s发送ping
        send_ping(){
            this.pingTimer = setInterval(()=>{
                this.socket.send(
                    JSON.stringfy({
                        type:'ping'
                    })
                );
            },50 * 1000);
        },
        //登录websocket
        login_websocket(){
            //登录数据处理...
            let login_data = {...};
            this.socket.send(JSON.stringfy(login_data));
            this.send_ping();
        },
    },
    destroyed(){
        clearInterval(this.pingTimer);
        this.socket.close();
    }
}
</script>