示例代码
前言,本代码用JS语言书写,自己使用环境是cocoscreatorv2.4.2版本,适用于小游戏长链接通信(未使用probuffer),可直接拿用。
let WebSocketUitils = {
socket: WebSocket,
helper: null,
isInit: false,
lockReconnect: false,
initWebSocket(){
let 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);
if(data.type == "heartBeat"){
this.timeoutNum = 3;
this.heartCheck();
}else{
this.helper.onmessage(data);
}
};
this.socket.onerror = (event)=>{
log.debug('websocket----------onerror---------->', event);
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));
this.timeoutNum--;
if(this.timeoutNum === 0) {
this.close();
this.reconnect();
}else{
this.heartCheck();
}
}, this.heartTime);
},
}
module.exports = WebSocketUitils;
至此,结束。
|