var uid = localStorage.getItem("uid"); var ws, obj = {}, lockReconnect = false; CreateWebSocket(); function CreateWebSocket() { try { Connect(); } catch(e) { ReConnect(); } } //连接 function Connect() { //ws = new WebSocket("ws://192.168.4.18:4006"); //ws = new WebSocket("ws://192.168.1.21:2021"); ws = new WebSocket("ws://117.158.196.116:4006"); ws.onopen = function() { console.log(new Date() + " " + "建立连接"); lockReconnect = false; obj.action = "cusconn"; obj.code = uid; Send(); }; //接收到消息的回调方法 ws.onmessage = function(evt) { console.log(new Date() + " receive " + evt.data); var data = JSON.parse(evt.data); if(data) { var type = data.action; switch(type.toLowerCase()) { case "cusconn": $(".main_message .chatlist_con").find("li").remove(); if(data.state) { localStorage.setItem("uid", data.code); } else { // $('.notice').html(''); notice("notice", data.msg); } if(data.code) { obj.action = "loglist"; obj.code = data.code; obj.msg = ""; Send(); } break; //case "servicerson": // append("notice", data.msg); // break; //通知客服上线 case "cussend": if(data.state) { append("self", data.msg,data.time); // document.getElementById("msg").value = ""; $('.send_content').val(''); } else { notice("notice", data.msg); // $('.notice').html(data.msg); } break case "cusreceive": append("left", data.msg,data.time) break; //收到消息 case "loglist": var list = data.data.rows; $(list).each(function(i, n) { var classname = "left"; if(n.F_FromUser == uid) { classname = "self"; } insert(classname, n.F_Message, $(".hidnum").val()); }) if(!data.data.isfirst) { $(".more").css("display", "block"); $(".hidnum").val(data.data.num); } else { $(".more").css("display", "none"); } break; //聊天记录 } } }; //连接关闭的回调方法 ws.onclose = function(evt) { console.log(new Date() + " " + "连接关闭"); console.log(new Date() + " " + "开始重连"); ReConnect(); }; //连接发生错误的回调方法 ws.onerror = function(evt) { console.log(new Date() + " " + "连接关闭"); console.log(new Date() + " " + "开始重连"); ReConnect(); }; } //重连 function ReConnect() { if(!lockReconnect) { lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多 setTimeout(function() { console.log(new Date() + " " + "重连中……"); lockReconnect = false; CreateWebSocket(); }, 2000); } } //发送 function Send() { if(ws.readyState != ws.OPEN) { ReConnect(); } if(ws.readyState == ws.OPEN) { console.log(new Date() + " send " + JSON.stringify(obj)); ws.send(JSON.stringify(obj)); } } //查看更多 function getmore() { obj.action = "loglist"; obj.code = localStorage.getItem("uid"); obj.msg = $(".hidnum").val(); Send(); } //发送消息 function sendinfo() { // var msg = document.getElementById("msg").value; var msg = $('.send_content').val(); if($.trim(msg)) { obj.action = "cussend"; obj.msg = msg; Send(); $(".error").text(""); } else { $('.send_content').val(''); $(".error").text("请输入内容"); } } function append(cname, msg,dates) { var html='