快捷搜索: 王者荣耀 脱发

websocket连接及心跳检测

var websocket = null;
var lockReconnect = false;
/**
 * 初始化websocket连接
 */
function initWebSocket() {
	webSocketInit();
}

/**
 * 连接ws
 */
function webSocketInit(){
	
	try{
		if(WebSocket in window) {
			websocket = new WebSocket(url);  //url为websocket地址
		} else {
			alert("该浏览器不支持websocket!");
		}
	}catch (e){
		websocketReconnect();  //尝试重连websocket
	}
	
	websocket.onopen = function(event) {
		console.log("建立连接");
		
	}
	websocket.onclose = function(event) {
		console.log(连接关闭)
		lockReconnect = false;
		websocketReconnect();  //尝试重连websocket
		
	}
	//建立通信后,监听到后端的数据传递过来了
	websocket.onmessage = function(event) {
		
		heartCheck.start();
	}
	websocket.onerror = function() {
		//alert(websocket通信发生错误!);
	}
	window.onbeforeunload = function() {
		websocket.close();
	}
}
/**
 * 重连ws
 */
function websocketReconnect(){
	if (lockReconnect) {       // 是否已经执行重连
		return;
	};
	lockReconnect = true;
	//没连接上会一直重连,设置延迟避免请求过多
	tt && clearTimeout(tt);
	var tt = setTimeout(function () {
		webSocketInit();
		lockReconnect = false;
		console.log("正在重连");
		heartCheck.start();
	}, 5000)
}


//心跳检测
var heartCheck = {
	timeout: 120000,
	timeoutObj: null,
	serverTimeoutObj: null,
	start: function () {
		console.log(start);
		var self = this;
		this.timeoutObj && clearTimeout(this.timeoutObj);
		this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
		this.timeoutObj = setTimeout(function () {
			//发送测试信息,后端收到后,返回一个消息,
			websocket.send(hello);
			self.serverTimeoutObj = setTimeout(function () {
				//websocket.close();
			}, self.timeout);
		}, this.timeout)
	}
}

/**
 * 发送ws消息
 */
function sendWsMsgTimer(){
	console.log("发送消息");
	connectTimer = window.setInterval(function(){
		websocket.send(hello);
	},120000);
	
}
经验分享 程序员 微信小程序 职场和发展