websocket:手机端实现、断线重连、心跳机制。并将内容推送到手机通知栏。
$(window).load(function() {
var windowUp = window.top ? window.top : window;
var lockReconnect = false;
var ws; //websocket对象
var initWebSocket = function() {
var wsUrl = "ws://example";//websocket-url
var count = 0; //消息数
//创建一个webSocket实例,执行后,客户端就会与服务端连接
ws = new WebSocket(wsUrl);
ws.onopen = function() {
alert("ws连接成功!");
count = 0;
console.log("WebSocket:Connected!");
ws.send("WebSocket:Connected!"); //传递信息
//开启心跳测试
heartCheck.reset().start();
};
ws.onmessage = function(evt) {
console.log("WebSocket:" + evt.data);
if (evt.data != "0000") {
count++;
//创建消息到通知栏
plus.push.createMessage(evt.data);
// 设置未读数(显示范围:1-99)
plus.runtime.setBadgeNumber(count);
}
//收到消息,重置心跳
heartCheck.reset().start();
};
ws.onclose = function(evt) {
alert("WebSocket:Closed!==" + JSON.stringify(evt));
console.log("WebSocket:Closed!==" + JSON.stringify(evt));
reconnect(wsUrl);
};
ws.onerror = function(evt) {
alert("WebSocket:Error!==" + JSON.stringify(evt));
console.log("WebSocket:Error!==" + JSON.stringify(evt));
reconnect(wsUrl);
};
}
//重连
function reconnect(url) {
if (lockReconnect) return;
lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多,每2秒重连一次
setTimeout(function() {
console.log("WebSocket:Reconnecting!");
initWebSocket();
lockReconnect = false;
}, 2000);
}
//心跳检测
var heartCheck = {
timeout: 50000, //50秒没收到回复,则说明后端主动断开了
timeoutObj: null,
serverTimeoutObj: null,
reset: function() {
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start: function() {
var self = this;
this.timeoutObj = setTimeout(function() {
//这里发送一个心跳,后端收到后,返回一个心跳消息,
//onmessage拿到返回的心跳就说明连接正常
console.log("心跳测试");
ws.send("0000");
self.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置,说明后端主动断开了
ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
}, self.timeout);
}, this.timeout);
}
}
if (windowUp.plus) {
initWebSocket();
} else {
document.addEventListener('plusready', initWebSocket, false);
}
});