_websocket.js
2.77 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
var gb_websocket = (function () {
var schSock = null;
var recInterval = null;
var reConnSpace = 1500;//重连间隔
var reConnCount; //重连次数
var maxReConn = 6; //最多重连次数
var new_conn = function () {
schSock = new SockJS('/sockjs/inout');
schSock.onopen = function (e) {
if(reConnCount && reConnCount > 1)
console.log('重新连接websocket');
reConnCount = 1;
clearInterval(recInterval);
console.log('webSocket[realcontrol] onopen');
$('.top_tools').removeClass('scok-colse');
};
//接收消息
schSock.onmessage = function (e) {
try {
var jsonMsg = $.parseJSON(e.data);
console.log('websocket...', jsonMsg);
msgHandle[jsonMsg.fn](jsonMsg);
} catch (e) {
console.log(e, e.data);
}
};
//断开
schSock.onclose = function (e) {
console.log('和服务器连接断开....', e);
$('.top_tools').addClass('scok-colse');
//1.5秒后重新连接
recInterval = setTimeout(function () {
reConnCount++;
if(reConnCount > maxReConn){
clearInterval(recInterval);
return;
}
new_conn();
}, reConnSpace * reConnCount);
};
};
//初始化websocket连接
new_conn();
var msgHandle = {
carIn: carInFun,
carOut: carOutFun,
abnormal_out: function (msg) {
gb_o_s_ws_handler.out(msg);
},
abnormal_att: function (msg) {
gb_o_s_ws_handler.attendace(msg);
},
all_rate_val: function (msg) {
gb_o_s_charts.changeVal(msg);
}
};
//websocket回调
var eventCallbacks = [];
function carInFun(msg) {
var text = msg['dataStr'] + " " +msg.nbbm + "进场" + (msg.berthName?(" 停泊位" + msg.berthName):"");
toastr.info(text);
gb_tts.speak(text);
//CCCallFuncN
$.each(eventCallbacks, function (i, cb) {
cb(msg);
});
}
function carOutFun(msg) {
var text = msg['dataStr'] + " " + msg.nbbm + " 出场";
toastr.info(text);
gb_tts.speak(text);
//CCCallFuncN
$.each(eventCallbacks, function (i, cb) {
cb(msg);
});
}
var registerCallback = function (cb) {
if (cb)
eventCallbacks.push(cb);
};
var cancelCallback = function (cb) {
if(cb){
removeByValue(eventCallbacks, cb);
}
};
return {
registerCallback: registerCallback,
cancelCallback: cancelCallback
}
})();