Vue项目全局创建WebSocket连接
首先创建WebSocket.js文件,我把它放在了src/js/websocket.js路径下
WebSocket.js:
import store from '@/store'
import { Message } from 'element-ui'
var url = 'ws://127.0.0.1:9090/websocket/'
var ws;
var tt;
var lockReconnect = false;//避免重复连接
var clientId = localStorage.getItem("clientId")//缓存中取出客户端id
var websocket = {
Init: function(clientId) {
if ("WebSocket" in window) {
ws = new WebSocket(url + clientId);
} else if ("MozWebSocket" in window) {
ws = new MozWebSocket(url + clientId);
} else {
console.log("您的浏览器不支持 WebSocket!");
return;
}
ws.onmessage = function(e) {
console.log("接收消息:" + e.data)
heartCheck.start()
if(e.data=='ok'){//心跳消息不做处理
return
}
//messageHandle(e.data)
}
ws.onclose = function() {
console.log("连接已关闭")
Message({
message: '连接已关闭',
type: 'error',
});
reconnect(clientId);
}
ws.onopen = function() {
console.log("连接成功")
Message({
message: '连接成功',
type: 'success',
});
heartCheck.start();
}
ws.onerror = function(e) {
console.log("数据传输发生错误");
Message({
message: '数据传输发生错误',
type: 'error',
});
reconnect(clientId)
}
},
Send:function(sender,reception,body,flag){
let data = {
sender:sender,
reception:reception,
body:body,
flag:flag
}
let msg= JSON.stringify(data)
console.log("发送消息:"+msg)
ws.send(msg)
},
getWebSocket(){
return ws;
},
getStatus(