vue调用websocket
代码片
.
var websock = null;
let rec;
let isConnect = false;
let checkMsg = "heartbeat";
var globalCallback = function() {};
let createWebSocket = () => {
try {
var ws = window.config.WebSocketapi;
websock = new WebSocket(ws);
initWebSocket();
} catch (e) {
console.log("尝试创建连接失败");
reConnect();
}
};
let reConnect = () => {
console.log("尝试重新连接");
if (isConnect) return;
rec && clearTimeout(rec);
rec = setTimeout(function() {
createWebSocket();
}, 5000);
};
let closeWebSocket = () => {
websock.close();
};
var heartCheck = {
timeout: 20000,
timeoutObj: null,
start: function() {
this.timeoutObj = setTimeout(function() {
if (isConnect) websock.send(checkMsg);
}, this.timeout);
},
reset: function() {
clearTimeout(this.timeoutObj);
this.start();
}
};
function initWebSocket() {
console.log(window.config.WebSocketapi)
var ws = window.config.WebSocketapi
websock = new WebSocket(ws)
websock.onclose = function(e) {
websocketclose(e)
}
websock.onopen = function() {
websocketOpen()
}
websock.onmessage = function(e) {
websocketonmessage(e)
}
websock.onerror = function() {
console.log('WebSocket连接发生错误')
isConnect = false;
reConnect();
}
}
function sendSock(agentData, callback) {
globalCallback = callback
if (websock.readyState === websock.OPEN) {
} else if (websock.readyState === websock.CONNECTING) {
setTimeout(function() {
sendSock(agentData, callback)
}, 1000)
} else {
setTimeout(function() {
sendSock(agentData, callback)
}, 1000)
}
}
function getSock(callback) {
globalCallback = callback
}
function websocketonmessage(e) {
console.log(e)
let webvalue = decodeUnicode(e.data)
if (!webvalue) {
heartCheck.reset();
} else {
globalCallback(webvalue);
}
function decodeUnicode(str) {
str = str.replace(/\\/g, "%");
str = unescape(str);
str = str.replace(/%/g, "\\");
str = str.replace(/\\/g, "");
return str;
}
}
function websocketclose(e) {
console.log(e)
isConnect = false;
}
function websocketOpen(e) {
console.log('socket连接成功')
}
initWebSocket()
export {
getSock,
createWebSocket,
closeWebSocket
}