webSocket连接

 created(){
            this.ws();
},
 methods:{
			ws(){
                // WebSocket
                if ("WebSocket" in window) {
                    //协议以及主机名的处理
                    const {host, protocol } = window.location;
                    const pro = protocol === "https:" ? "wss://" : "ws://";
                    let ws = new WebSocket(`${pro}${host}/api/rates?id=${this.query}`);
                    
                    // 连接错误
                    ws.onerror = this.setErrorMessage;

                    // 连接成功
                    ws.onopen = this.setOnopenMessage;

                    // 收到消息的回调
                    ws.onmessage = this.setOnmessageMessage;

                    // 连接关闭的回调
                    ws.onclose = this.setOncloseMessage;

                    // 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
                    window.onbeforeunload = this.onbeforeunload;
                } else {
                    alert("当前浏览器 Not support websocket");
                }
            },
            setErrorMessage() {
                console.log(this.websocket)
                console.log( "WebSocket连接发生错误   状态码:" + this.websocket.readyState);
            },
            setOnopenMessage() {
                console.log("WebSocket连接成功    状态码:" + this.websocket.readyState);
            },
            setOnmessageMessage(event) {
                // 服务器推送的消息
                // console.log("服务端返回:" + event.data);
                // console.log(event)
                
               //从event.data里面拿到连接返回的数据
            },
            setOncloseMessage() {
                console.log("WebSocket连接关闭    状态码:" + this.websocket.readyState);
            },
            onbeforeunload() {
                this.closeWebSocket();
            },
            closeWebSocket(ws) {
                ws.close;
            },
            
            //断开连接的方法
            blockUpload(scope){
            //我这里的ws是从参数里面传过来的,可以根据自己的项目情况来看
                this.closeWebSocket(scope.ws); 
            },
}

你可能感兴趣的:(经验,websocket)