/** * Created by dengbk on 2019/3/25. */ layui.define(['layer'],function(exports){ var vciWebSocket = function(){ this.url = { //$webUtil.getCurrentUserId() wsUrl:"ws://172.16.0.54:10000/vciMessageServer/mes208/"+$webUtil.getCurrentUserId()+"/"+$webUtil.getCurrentUserId()+""//websocket地址 }; this.websocket_connected_count = 0; this.onclose_connected_count = 0; this.config = { //wsUrl:"ws://localhost:10000/vciMessageServer/mes208/renky/renky",//服务器地址 onopen:function(){ //握手成功 }, onmessage:function(data){ //收到消息 } }; this.serverTimeoutObj = "";//心跳 this.linkSocket = ""; }; vciWebSocket.prototype.init = function(){ var that = this; if(typeof(WebSocket) == "undefined") { console.log("您的浏览器不支持WebSocket"); }else{ console.log("您的浏览器支持WebSocket"); that.linkSocket = new WebSocket(that.url.wsUrl); that.linkSocket.onopen = function() { console.log("Socket 已打开"); that.config.onopen() }; //获得消息事件 that.linkSocket.onmessage = function(msg) { console.log(msg); that.heartCheck() that.config.onmessage(msg) }; //关闭事件 that.linkSocket.onclose = function(e) { console.log("Socket已关闭"); console.log(e); }; //发生了错误事件 that.linkSocket.onerror = function() { that.websocket_connected_count++; if(that.websocket_connected_count <= 5){ } console.log("Socket发生了错误"); } } }; vciWebSocket.prototype.heartCheck = function(){ var that = this; that.heartCheckReset(); that.heartCheckStart() }; vciWebSocket.prototype.heartCheckReset = function(){ var that = this; clearTimeout(that.serverTimeoutObj); }; vciWebSocket.prototype.heartCheckStart = function(){ var that = this; this.serverTimeoutObj = setInterval(function(){ if(that.linkSocket.readyState == 1){ console.log("连接状态,发送消息保持连接"); that.linkSocket.send("ping"); // that.heartCheck() // 如果获取到消息,说明连接是正常的,重置心跳检测 }else{ console.log("断开状态,尝试重连"); } }, 60000) }; exports('vciWebSocket',new vciWebSocket()) });