示例代码
前言,本代码用JS语言书写,自己使用环境是cocoscreatorv2.4.2版本,适用于小游戏长链接通信(未使用probuffer),可直接拿用。代码中用到的log.debu日志打印函数,是我自己的一层日志打印封装。
let WebSocketUitils = {
socket: WebSocket,//声明变量类型
helper: null,//事件分发中转对象
isInit: false,//是否初始化完成
lockReconnect: false,//是否正在重连
//初始化websocket
initWebSocket(){
let host = '';//ws地址
// log.debug('websocket----connect:', host);
this.socket = new WebSocket(host);
this.socket.onopen = (event)=>{
log.debug('websocket----------onopen---------->', event);
this.isInit = true;
this.lockReconnect = false;
this.tryReconnect = null;
this.timeoutNum = 3;
this.heartCheck();
};
this.socket.onmessage = (event)=>{
let data = event.data;
data = JSON.parse(data);
// log.debug('websocket----------onmessage---------->', data);
if(data.type == "heartBeat"){
//重置心跳超时次数
this.timeoutNum = 3;
//发送心跳
this.heartCheck();
}else{
//事件分发
this.helper.onmessage(data);
}
};
this.socket.onerror = (event)=>{
log.debug('websocket----------onerror---------->', event);
//重连(此处可不进行重连,因onerror调用后、会onclose方法会被调用触发重连)
//this.socket = null;
//this.reconnect();
};
this.socket.onclose = (event)=>{
log.debug('websocket----------onclose---------->', event);
//重连
this.socket = null;
this.reconnect();
};
},
send(data){
log.debug('发送消息~~~~~~~~~~~~', data);
if (!this.isInit){
log.debug('WebSocket is not inited...');
}else if(this.socket.readyState == WebSocket.OPEN){
log.debug('WebSocket send:', data);
this.socket.send(data);
}else{
log.debug('WebSocket readState:', this.socket.readyState);
}
},
close(){
if (this.socket){
log.debug("WebSocket close...");
this.socket.close();
this.socket = null;
}
},
//重连
tryReconnect: null,
reconnect() {
//判断是否正在重连
if(this.lockReconnect) {
return;
};
this.lockReconnect = true;
//没连接上会一直重连,设置延迟避免请求过多
this.tryReconnect && clearTimeout(this.tryReconnect);
this.tryReconnect = setTimeout(()=>{
this.initWebSocket();
}, 4000);
},
/*~~~~~~~~~~~~~~~~~~~~~~~~~~心跳~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
timeoutNum: 3,//超过三次进行重连
heartTime: 3000, //每隔三秒发送心跳
heartObj: null,
heartCheck(){
this.heartObj && clearTimeout(this.heartObj);
this.heartObj = setTimeout(()=>{
//发送一个心跳,后端收到后,返回一个心跳消息,拿到返回的心跳就说明连接正常
let msg = {"msg": "ping"};
this.socket && this.socket.send(JSON.stringify(msg));// 心跳包
//3次心跳均未响应重连
this.timeoutNum--;
//计算答复的超时次数
if(this.timeoutNum === 0) {
this.close();
this.reconnect();
}else{
this.heartCheck();
}
// log.debug('心跳~~~~~~~~~~~~~~~~~~~~~~', this.heartObj);
}, this.heartTime);
},
}
module.exports = WebSocketUitils;
至此,结束。