socket.js
2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import store from '../store'
import axios from './http'
import * as API from './api'
window.PushWs = null;
window.pushwsurl = null;
window.pushwsClock = null;
var sessionID = ''
export const pushws = function getpushws() {
let userName = localStorage.getItem("user_id");
let clientTimer = new Date().getTime();
sessionID = clientTimer;
axios.get(API.url + "/manage/push/ws_url?src_type=user&user_unid=" + userName + "&client_unid=" + clientTimer,{
headers: {
'authorization': localStorage.getItem('atoken')
}
})
.then(response => {
openWs("pushws", response.data.ws_url);
pushwsurl = response.data.ws_url;
});
}
function openWs(wstype, wsUrl) {
if ("WebSocket" in window) {
if (wstype == "pushws") PushWs = new WebSocket(wsUrl);
} else if ("MozWebSocket" in window) {
if (wstype == "pushws") PushWs = new MozWebSocket(wsUrl);
} else {
if (wstype == "pushws") PushWs = new SockJS(wsUrl);
}
/**
* 报警推送
*/
try {
PushWs.onerror = function (event) {
console.log("推送WebSocket:发生错误 ");
console.log("错误" + event);
};
PushWs.onclosed = function () {
getpushws();
console.log("推送服务ws关闭")
};
PushWs.onopen = function (event) {
debugger
console.log("推送WebSocket:已连接");
store.commit('setsessionID',sessionID)
pushwsClock = setInterval(wsPushclock, 20000);
};
/**
* 处理接收到的数据
* @param {*} event
*/
PushWs.onmessage = function (event) {
var data = JSON.parse(event.data);
store.dispatch("GetAlarmData", data)
if (data.command == "post /wsapi/v1/event/black_face_events") {
}
}
} catch (err) {
console.log(err);
}
/**
* 推送心跳
*/
function wsPushclock(command) {
let date = new Date();
let datatimes = date.getTime();
if (PushWs.readyState == 1) {
try {
let PushMessage = {
type: "request",
id: datatimes + 1,
command: "get /wsapi/v1/dtid/" + pushwsurl.split('connects/')[1] + "/keep_alive", //推送服务
mts: datatimes
};
PushWs.send(JSON.stringify(PushMessage));
} catch (err) {
console.log(err);
}
} else {
clearInterval(pushwsClock);
pushws();
}
}
}