WebSocket协议的客户端程序
连接到WS服务器
向WS服务器发消息并接收消息
断开与WS服务器的连接
var wsClient=null;var lastHealthTime = 0; //记录最近一次心跳更新时间
var heartbeatTimer = null;//心跳执行timer
var checkTime = 10000; //心跳检查时间间隔-毫秒 10秒
var healthTimeOut = 20000;//心跳时间间隔-毫秒 20秒
var reconnectTimer = null;//重连接timer
var reconnectTime = 10000;//重连接时间10秒后
var uid = "20";var connectStatus = 3; //状态
function connect(){if (connectStatus == 3){
wsClient=new WebSocket('ws://127.0.0.1:8000'); //这个端口号和容器监听的端口号一致
console.log("连接中...");
console.log("readyState:"+wsClient.readyState);if(reconnectTimer){
clearTimeout(reconnectTimer);
}//连接成功
wsClient.onopen =function(){
connectStatus=wsClient.readyState;//表名自己是uid1
var data = uid; //1标识连接wsClient.send(data);
console.log('ws客户端已经成功连接到服务器上');
msg.innerHTML="连接成功...";
console.log("readyState:"+wsClient.readyState);var time = newDate();
lastHealthTime=time.getTime();if(heartbeatTimer){
clearInterval(heartbeatTimer);
}
heartbeatTimer=setInterval(function(){keepalive(wsClient)}, checkTime);
};//收到消息
wsClient.onmessage =function(e){
console.log('ws客户端收到一个服务器消息:'+e.data);
console.log("readyState:"+wsClient.readyState);
val.innerHTML=e.data;var data =e.data;if(data){var msg_type = data.substr(0,1);var uid = data.substr(1);var time = newDate();
lastHealthTime=time.getTime();//更新客户端的最后一次心跳时间
}
}//错误
wsClient.onerror =function(e){
connectStatus=wsClient.readyState;
console.log("error");
console.log("readyState:"+wsClient.readyState);
msg.innerHTML="连接错误...";
};//关闭
wsClient.onclose =function(){
connectStatus=wsClient.readyState;
console.log('到服务器的连接已经断开');
msg.innerHTML="连接断开...";
console.log("readyState:"+wsClient.readyState);//n秒后重连接
reconnectTimer =setTimeout(function(){
connect();
},reconnectTime);
}
}
}
btConnect.οnclick=function(){
connect();
}
btSendAndReceive.οnclick=function(){
wsClient.send('Hello Server');
}
btClose.οnclick=function(){
console.log("断开连接");
console.log(wsClient.readyState);
wsClient.close();
}
function keepalive(ws){var time = newDate();
console.log(time.getTime()-lastHealthTime);if ((time.getTime()-lastHealthTime)>healthTimeOut){
msg.innerHTML="心跳超时,请连接断开...";if(heartbeatTimer){
clearInterval(heartbeatTimer);//n秒后重连接
ws.close();
reconnectTimer=setTimeout(function(){
connect();
},reconnectTime);
}
}else{
msg.innerHTML="我依然在连接状态";ws.send(data);
}
}