zhuguoqing ff550d5d6a init
2022-05-22 10:32:02 +08:00

123 lines
3.4 KiB
JavaScript

/**
* Created by Y.X on 16/7/6.
*/
var MessageBuffer = require('msgbuffer');
var MessageVo = require('messageVo');
var WS = require('webclient');
//var Base64 = require('base64');
var MsgManager = cc.Class({
name: "MsgManager",
init:function() {
this._sendMsgQueue = {};
this._recvMsgQueue = {};
this._ws = new WS();
this._ws.setCallback(this);
this._buf = new MessageBuffer();
this._buf.init();
this._isconnected = false;
this._netcb = null;
},
initSendMsg:function(msgId, proto) {
var vo = new MessageVo();
vo.update(msgId, proto, null);
this._sendMsgQueue[msgId] = vo;
},
initRecvMsg:function(msgId, proto, callBack) {
var vo = new MessageVo();
vo.update(msgId, proto, callBack);
this._recvMsgQueue[msgId] = vo;
},
sendMsg:function(msgId, msg) {
// cc.log("请求信息id:" + msgId+"=="+msg);
var msgVo = this._sendMsgQueue[msgId];
// console.log("test"+JSON.stringify(msgVo));
var data = msg? msgVo.protoData.encode(msg).toArrayBuffer():null;
//cc.log("发送消息中..." + JSON.stringify(data));
var pkgdata = this._buf.buildPackMsg(msgId, data);
if(pkgdata && this._ws){
//console.log(Base64.arrayBufferToBase64(pkgdata));
//console.log("[sendmsg]:"+msgId + ":" + msg);
this._ws.send(pkgdata);
}
//cc.log("发送消息成功!");
},
parseMsg:function(msgId, msgByte) {
// console.log("信息回调id:" + msgId+ ":"+msgByte);
var msgVo = this._recvMsgQueue[msgId];
if(msgVo == undefined){
console.log("[undefined msg]"+msgId);
return;
}
var msg = msgVo.protoData.decode(msgByte);
if(msgVo.callBack) {
//统一处理errorcode
if(msg && msg.errorcode){
//TODO 统一处理errorcode
//1:根据errorcode获取对应的文本信息
//2:提示给用户
}
msgVo.callBack(msg,msgId);
}
},
isConnected(){
return this._isconnected;
},
connectNet: function(host, cb){
console.log("准备链接socket---------------");
this._netcb = cb;
//this._ws.setHost(host);
this._ws.url = host;
this._ws.connect();
},
closeNet: function(){
this._ws.disconnect();
},
onConnect:function(){
console.log("onConnectonConnectonConnectonConnect")
this._isconnected = true;
if(this._netcb){
this._netcb("connect", 0);
}
},
onClose:function(err){
console.log("onCloseonCloseonCloseonCloseonClose")
this._isconnected = false;
if(this._netcb){
var n = err.code? err.code: 0;
this._netcb("close", n);
}
},
onError:function(err){
console.log("onErroronErroronErroronErroronError")
this._isconnected = false;
if(this._netcb){
var n = err.code? err.code: 0;
this._netcb("error", n);
}
},
onRecv:function(msg){
// console.log("onrecv");
this._buf.pushData(msg);
while(this._buf.hasPackMsg()){
var msg = this._buf.popPackMsg();
this.parseMsg(msg.id(), msg.data());
}
}
});
module.exports = MsgManager;