/** * 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) { var msgVo = this._sendMsgQueue[msgId]; var data = msg? msgVo.protoData.encode(msg).toArrayBuffer():null; 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); } }, parseMsg:function(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) { if(msg && msg.errorcode){ } msgVo.callBack(msg,msgId); } }, isConnected(){ return this._isconnected; }, connectNet: function(host, cb){ this._netcb = cb; //this._ws.setHost(host); this._ws.url = host; this._ws.connect(); }, closeNet: function(){ this._ws.disconnect(); }, onConnect:function(){ this._isconnected = true; if(this._netcb){ this._netcb("connect", 0); } }, onClose:function(err){ this._isconnected = false; if(this._netcb){ var n = err.code? err.code: 0; this._netcb("close", n); } }, onError:function(err){ 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;