From e400a75fa41db579e16e5f8bb61573e79dc05ff3 Mon Sep 17 00:00:00 2001 From: java110 <928255095@qq.com> Date: Fri, 5 Jun 2020 13:48:44 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=A0=E5=85=A5websocket?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/components/frame/nav/nav.js | 54 ++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/public/components/frame/nav/nav.js b/public/components/frame/nav/nav.js index 6838dd693..63fc792ac 100644 --- a/public/components/frame/nav/nav.js +++ b/public/components/frame/nav/nav.js @@ -202,4 +202,58 @@ vm.getUserInfo(); + //建立websocket 消息连接 + let _userId = vc.getData('/nav/getUserInfo').userId; + + var url = + "ws://"+window.location.host+"/websocket/message/" + + _userId; + if ("WebSocket" in window) { + websocket = new WebSocket(url); + } else if ("MozWebSocket" in window) { + websocket = new MozWebSocket(url); + } else { + websocket = new SockJS(url); + } + + //连接发生错误的回调方法 + websocket.onerror = function() { + console.log("初始化失败"); + this.$notify.error({ + title: "错误", + message: "连接失败,请检查网络" + }); + }; + + //连接成功建立的回调方法 + websocket.onopen = function() { + console.log("ws初始化成功"); + }; + + //接收到消息的回调方法 + websocket.onmessage = function(event) { + console.log("event", event); + //let _data = event.data; + let _data = JSON.parse(_data); + if(_data.code == 200){ + toastr.info(_data.msg); + }else{ + toastr.error(_data.msg); + } + }; + + //连接关闭的回调方法 + websocket.onclose = function() { + console.log("初始化失败"); + this.$notify.error({ + title: "错误", + message: "连接关闭,请刷新浏览器" + }); + }; + + //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 + window.onbeforeunload = function() { + websocket.close(); + }; + })(window.vc); \ No newline at end of file