$(function () {
createWebSocket(wsServer);//建立socket连接
});
//WebSocket连接后台开始
var lockReconnect = false; //避免ws重复连接
var ws = null;
var wsServer = "";//ws地址
var httpServer = "";//http地址
//创建WebSocket对象
function createWebSocket(wsServer){
if ('WebSocket' in window) {
ws = new WebSocket(wsServer);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(wsServer);
} else {
ws = new SockJS(httpServer);
}
// Socket创建并连接
ws.onopen = function(evt) {
heartCheck.reset().start();
// layer.msg("已建立连接正在聊天", {
// offset : 0
// });
//return;
};
// Socket 消息传递监听
ws.onmessage = function(evt) {
heartCheck.reset().start();
analysisMessage(evt.data); //解析后台传回的消息,并予以展示
};
// Socket异常监听
ws.onerror = function(evt) {
console.log("产生Socket异常");
reconnect(wsServer);
};
// Socket关闭监听
ws.onclose = function(evt) {
console.log("已关闭Socket连接");
reconnect(wsServer);
//return;
};
//WebSocket连接后台结束
}
function reconnect(url) {
if(lockReconnect) {
return;
}
lockReconnect = true;
setTimeout(function () {
createWebSocket(url);
lockReconnect = false;
}, 2000);
}
/**
* 发送信息给后台
*/
function sendMessage() {
if (ws == null) {
layer.msg("未开启Socket连接!", {
offset : 0,
shift : 6
});
return;
}
var message = $("#message").val();
if (message == null || message == "") {
layer.msg("发送内容不能为空!", {
offset : 0,
shift : 6
});
return;
}
// 客户端向服务端发送消息
ws.send(JSON.stringify({
message : {
//发送的消息内容给服务器
}
}));
}
//解析后台传回的消息,并予以展示
function analysisMessage(message) {
console.log(JSON.parse(message))
message = JSON.parse(message);
}
//心跳检测
var heartCheck = {
timeout: 60000,//60秒
timeoutObj: null,
reset: function(){
clearTimeout(this.timeoutObj);
return this;
},
start: function(){
this.timeoutObj = setTimeout(function(){
//onmessage拿到返回的心跳就说明连接正常
console.log("心跳检测");
ws.send("心跳检测");
}, this.timeout)
}
}