其他不需要改 ,,,只要改wsUrl变量,代码逻辑在doWithMsg函数中,因为还有心跳检测,会向后端发送心跳数据,需要返回数据,这个要后端配合下
<script> var ws;//websocket实例 var lockReconnect = false;//避免重复连接 var wsUrl = "xxx"; function createWebSocket(url) { try { if (‘WebSocket‘ in window) { ws = new WebSocket(url); initEventHandle(); }else{ console.log(‘您的浏览器不支持websocket‘) } } catch (e) { reconnect(url); } } function initEventHandle() { ws.onclose = function (evnt) { //console.log(‘websocket服务关闭了‘); reconnect(wsUrl); }; ws.onerror = function (evnt) { //console.log(‘websocket服务出错了‘); reconnect(wsUrl); }; ws.onopen = function (evnt) { //心跳检测重置 heartCheck.reset().start(); }; ws.onmessage = function (evnt) { //如果获取到消息,心跳检测重置 //拿到任何消息都说明当前连接是正常的 //console.log(‘websocket服务获得数据了‘); //接受消息后的UI变化 doWithMsg(evnt.data); heartCheck.reset().start(); } //收到消息推送 function doWithMsg(msg) { // json数据转换成js对象 var data = eval("(" + msg + ")"); var type = data.type || ‘‘; switch (type) { // 返回的init类型的消息,将client_id发给后台进行uid绑定 case ‘init‘: // 利用jquery发起ajax请求,将client_id发给后端进行uid绑定 // $.post(‘./bind.php‘, {client_id: data.client_id}, function(data){}, ‘json‘); break; case ‘content‘: var value = array[Math.round(Math.random()*(array.length-1))]; // var data = JSON.parse(JSON.stringify(data.data)) break; default: console.log(data); } } } function reconnect(url) { if(lockReconnect) return; lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 setTimeout(function () { createWebSocket(url); lockReconnect = false; }, 5000); } //心跳检测 var heartCheck = { timeout: 60000,//60秒 timeoutObj: null, serverTimeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj); return this; }, start: function(){ var self = this; this.timeoutObj = setTimeout(function(){ //这里发送一个心跳,后端收到后,返回一个心跳消息, //onmessage拿到返回的心跳就说明连接正常 ws.send("HeartBeat"); self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了 ws.close();//如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次 }, self.timeout) }, this.timeout) } } //初始化websocket createWebSocket(wsUrl); </script>