Connect.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import DataModelBase from '../framework/DataModelBase';
  2. import Event from './Event';
  3. import Common from '../common/Common';
  4. import CCipher from '../common/CCipher';
  5. import Packet from '../net/Packet';
  6. import ConstMsgId from '../net/ConstMsgId';
  7. import MsgTransfer from '../net/MsgTransfer';
  8. import Define from '../common/Define';
  9. //var protobuf = require("protobufjs");
  10. //var PBTransfer = require("PBTransfer");
  11. //var ByteBuffer = protobuf.ByteBuffer;
  12. export default class Connect extends DataModelBase
  13. {
  14. constructor(url,isShortConnect)
  15. {
  16. super('Connect');
  17. this._url = url;
  18. Common.Print('Connect url:' + url);
  19. this._isShortConnect = isShortConnect;
  20. this._state = Common.SocketState.Closed;
  21. this._webSocket = null;
  22. this._protoLoaded = false;
  23. this._protoMsgClass = {};
  24. this._messageIndex = 0;
  25. this._bNeedClose = false; // 客户端需要被主动关闭
  26. this._reConnectInterval = 3000;
  27. this._bReconnect = false;
  28. this._closeTimeOut = null;
  29. this._errorTimeOut = null;
  30. this._timeOut = null;
  31. this._sendDataBuf = new Array();
  32. this._heatInterval = 15000;//15 second
  33. this._pingTimes = 0;
  34. this._socketType = Define.SOCKET_TYPE.PLAZA
  35. }
  36. // var protoFiles = [
  37. // ["resources/proto/authmsg.proto", "./authmsg.proto"],
  38. // ["resources/proto/commsg.proto", "./commsg.proto"],
  39. // ["resources/proto/gamemsg.proto", "./gamemsg.proto"]
  40. // ];
  41. //加载proto文件,在游戏初始时进行,推荐在资源加载时调用
  42. //需要等待proto全部加载完成之后,才能使用socket
  43. loadProto (protoFiles,callback)
  44. {
  45. let con = this
  46. con._protoMsgClass = {};
  47. cc.loader.loadResDir("proto", function(err, array)
  48. {
  49. for (var i=0, dep, data; i<protoFiles.length; i++)
  50. {
  51. dep = protoFiles[i];
  52. var realUrl = cc.url.raw(dep[0]);
  53. var proto_msg = array[i].text;
  54. var msg_builder = protobuf.loadProto(proto_msg, dep[1]);
  55. con.analiseNameSpace(msg_builder, con._protoMsgClass);
  56. }
  57. con._protoLoaded = true;
  58. Common.Print('_protoLoaded '+ con._protoLoaded);
  59. PBTransfer.setProtoClassHolder(con._protoMsgClass);
  60. if(callback)
  61. {
  62. callback.call();
  63. }
  64. });
  65. }
  66. //解析一个proto ns,将其中所有的builder都缓存起来
  67. analiseNameSpace (builder, classHolder)
  68. {
  69. if(!builder)
  70. return;
  71. if(!classHolder)
  72. return;
  73. if(!builder.ns)
  74. return;
  75. var children = builder.ns.children;
  76. if(!children)
  77. return;
  78. var child = children[0];
  79. if(!child)
  80. return;
  81. var packageName = "";
  82. //has package;
  83. while(child.className == "Namespace")
  84. {
  85. if(packageName.length == 0)
  86. packageName += child.name;
  87. else
  88. packageName += "." + child.name;
  89. children = child.children;
  90. if(!children)
  91. return;
  92. child = children[0];
  93. if(!child)
  94. return;
  95. }
  96. for(var child of children)
  97. {
  98. var name = child.name;
  99. if(!name)
  100. continue;
  101. if(packageName.length == 0)
  102. classHolder[name] = builder.build(name);
  103. else
  104. classHolder[name] = builder.build(packageName + "." + name);
  105. }
  106. }
  107. getConnectState()
  108. {
  109. if(this._webSocket == null)
  110. {
  111. return this._state;
  112. }
  113. if(this._webSocket.readyState == WebSocket.CONNECTING)
  114. {
  115. this._state = Common.SocketState.Connecting;
  116. }
  117. else if(this._webSocket.readyState == WebSocket.OPEN)
  118. {
  119. this._state = Common.SocketState.OK;
  120. }
  121. else if(this._webSocket.readyState == WebSocket.CLOSING)
  122. {
  123. this._state = Common.SocketState.Closing;
  124. }
  125. else if(this._webSocket.readyState == WebSocket.CLOSED)
  126. {
  127. this._state = Common.SocketState.Closed;
  128. }
  129. else
  130. {
  131. //noting to do
  132. }
  133. //Common.Print("this._state:" + this._state);
  134. return this._state;
  135. }
  136. open( bReconnect)
  137. {
  138. Common.Print(" connect open" + this._url)
  139. this._bNeedClose = false
  140. if(this._timeOut != null)
  141. {
  142. clearTimeout(this._timeOut);
  143. this._timeOut = null;
  144. }
  145. if(!this._url || typeof(this._url) !== "string" || this._url.length == 0)
  146. return -1;
  147. if(this._state == Common.SocketState.Connecting)//正在连接中......
  148. {
  149. // return this._state;
  150. Common.Print(" connect open Common.SocketState.Connecting")
  151. return 0
  152. }
  153. if(bReconnect == true)
  154. {
  155. this._bReconnect = true;
  156. this.emit(Event.SOCKET_MSG.RECONNECT_START);
  157. }
  158. this.close()
  159. this._bNeedClose = false; // 客户端主动关闭
  160. this._webSocket = null;
  161. console.log('open:cc.sys.os: ' + cc.sys.os + ' CC_JSB:' + CC_JSB + ' cc.sys.isMobile:' + cc.sys.isMobile)
  162. if(CC_JSB && cc.sys.OS_ANDROID === cc.sys.os)
  163. {
  164. var pemUrl = cc.url.raw('resources/key/server.pem')
  165. if(cc.loader.md5Pipe)
  166. {
  167. pemUrl = cc.loader.md5Pipe.transformURL('resources/key/server.pem')
  168. }
  169. //this._webSocket = new WebSocket(this._url,'',pemUrl);
  170. this._webSocket = new WebSocket(this._url);
  171. }
  172. else
  173. {
  174. this._webSocket = new WebSocket(this._url);
  175. }
  176. this._webSocket.binaryType = "arraybuffer";
  177. this._webSocket.onopen = this._onOpen.bind(this);
  178. this._webSocket.onmessage = this._onMessage.bind(this);
  179. this._webSocket.onerror = this._onError.bind(this);
  180. this._webSocket.onclose = this._onClose.bind(this);
  181. this._state = Common.SocketState.Connecting;
  182. return 0;
  183. }
  184. //主动关闭连接
  185. close()
  186. {
  187. if(!this._webSocket || !(this._webSocket instanceof WebSocket))
  188. return -1;
  189. if(this.getConnectState() == Common.SocketState.Closed)
  190. return this._state;
  191. this._state = Common.SocketState.Closed;
  192. this._webSocket.close();
  193. this._messageIndex = 0;
  194. this._bNeedClose = true; // 客户端主动关闭
  195. this._bReconnect = false;
  196. }
  197. sendSocketData(wMain, wSub, pData,wDataSize)
  198. {
  199. }
  200. sendMsg(msg)
  201. {
  202. CCipher.encryptBuffer(msg,msg.byteLength)
  203. this._sendData(msg)
  204. }
  205. getUrl()
  206. {
  207. return this._url;
  208. }
  209. /////////////////////////////////////////私有方法和属性/////////////////////////////////////
  210. //连接监听
  211. _onOpen (evt)
  212. {
  213. Common.Print('Connect _onOpen start')
  214. this._bNeedClose = false; // 客户端主动关闭
  215. this._state = Common.SocketState.OK;
  216. this._pingTimes = 0;
  217. if(this._bReconnect == true)
  218. {
  219. this.emit(Event.SOCKET_MSG.RECONNECT_OK);
  220. this._bReconnect = false;
  221. }
  222. this.emit(Event.SOCKET_MSG.OPEN)
  223. if(this._closeTimeOut != null)
  224. {
  225. clearTimeout(this._closeTimeOut);
  226. this._closeTimeOut = null;
  227. }
  228. if(this._errorTimeOut != null)
  229. {
  230. clearTimeout(this._errorTimeOut);
  231. this._errorTimeOut = null;
  232. }
  233. if(this._timeOut != null)
  234. {
  235. clearTimeout(this._timeOut);
  236. this._timeOut = null;
  237. }
  238. this.checkHeartBeat();
  239. Common.Print('Connect _onOpen end')
  240. }
  241. sendBufData()
  242. {
  243. for (var i = 0; i < this._sendDataBuf.length ; i++)
  244. {
  245. this.sendData(this._sendDataBuf[i].msgid,this._sendDataBuf[i].msgdata);
  246. }
  247. this._sendDataBuf = [];
  248. }
  249. //返回监听
  250. _onMessage (evt)
  251. {
  252. //解析返回的消息
  253. // 粘包、拆包
  254. // if (evt.data instanceof Blob)
  255. // {
  256. // console.log("Blob")
  257. // }
  258. if(typeof(evt.data)=="string")
  259. {
  260. console.log("string")
  261. }
  262. Common.Print('Connect _onMessage')
  263. console.log(evt.data)
  264. Common.Print(typeof(evt.data))
  265. var dataview = new DataView(evt.data)
  266. var dataviewLength = evt.data.byteLength
  267. if(dataviewLength < Packet.TCPInfoSize) //
  268. {
  269. console.log("dataviewLength< Packet.TCPInfoSize(4)")
  270. return
  271. }
  272. CCipher.decryptBuffer(evt.data,evt.data.byteLength)
  273. var readPos = 0
  274. var cbDataKind = dataview.getUint8(readPos,Common.littleEndian)
  275. readPos +=1
  276. var cbCheckCode = dataview.getUint8(readPos,Common.littleEndian)
  277. readPos +=1
  278. var wPacketSize = dataview.getUint16(readPos,Common.littleEndian)
  279. readPos +=2
  280. var wMainCmdID = dataview.getUint16(readPos,Common.littleEndian)
  281. readPos +=2
  282. var wSubCmdID = dataview.getUint16(readPos,Common.littleEndian)
  283. readPos +=2
  284. if(wMainCmdID != ConstMsgId.MDM_KN_COMMAND && wSubCmdID != ConstMsgId.SUB_KN_DETECT_SOCKET )
  285. {
  286. Common.Print("_onMessage wMainCmdID:" + wMainCmdID + " wSubCmdID:" + wSubCmdID + " wPacketSize:" + wPacketSize)
  287. }
  288. if(wMainCmdID == ConstMsgId.MDM_KN_COMMAND && wSubCmdID == ConstMsgId.SUB_KN_DETECT_SOCKET)
  289. {
  290. this.pingTimes = this.pingTimes - 1
  291. }
  292. if(wMainCmdID > 0 || wSubCmdID != Packet.SUB_KN_DETECT_SOCKET)
  293. {
  294. var pack = null
  295. if(dataviewLength > Packet.TCPInfoSize)
  296. {
  297. var packBuf = evt.data.slice(Packet.TCPHeadSize,dataviewLength)
  298. }
  299. this.emit(Event.SOCKET_MSG.DATA, wMainCmdID,wSubCmdID,packBuf)
  300. }
  301. }
  302. //错误监听
  303. _onError(evt) {
  304. //GH.log("GameSocket _onError", evt);
  305. console.log(Common.GetDateString() + 'GameSocket _onError'+ JSON.stringify(evt))
  306. let self = this;
  307. this._state = Common.SocketState.Error;
  308. if(this._timeOut!=null)
  309. {
  310. clearTimeout(this._timeOut);
  311. this._timeOut = null;
  312. }
  313. if(this._bNeedClose != true)
  314. {
  315. this._errorTimeOut = setTimeout(function() {
  316. self.open(true);
  317. }, self._reConnectInterval);
  318. }
  319. this.emit(Event.SOCKET_MSG.ERROR);
  320. }
  321. //关闭监听
  322. _onClose(evt)
  323. {
  324. console.log(Common.GetDateString() + 'GameSocket _onClose'+ JSON.stringify(evt))
  325. var state = this.getConnectState()
  326. console.log(Common.GetDateString() + 'GameSocket _onClose state :'+ state)
  327. if( Common.SocketState.OK == state )
  328. {
  329. return
  330. }
  331. this._state = Common.SocketState.Closed;
  332. var bClientClosed = this._bClientClosed;
  333. let self = this;
  334. if(this._timeOut!=null)
  335. {
  336. clearTimeout(this._timeOut);
  337. this._timeOut = null;
  338. }
  339. if(this._bNeedClose != true)
  340. {
  341. this._closeTimeOut = setTimeout(function() {
  342. self.open(true);
  343. }, self._reConnectInterval);
  344. }
  345. this.emit(Event.SOCKET_MSG.CLOSE,bClientClosed);
  346. }
  347. _sendData(dataBuf)
  348. {
  349. if(!dataBuf || !(dataBuf instanceof ArrayBuffer))
  350. return -1;
  351. if (!this._webSocket)
  352. return -1;
  353. if(this.getConnectState() != Common.SocketState.OK)
  354. {
  355. return this._state;
  356. }
  357. if (this._webSocket.readyState === WebSocket.OPEN) {
  358. console.log('_sendData')
  359. this._webSocket.send(dataBuf);
  360. return 0;
  361. } else {
  362. this._state = this.getConnectState();
  363. //this._webSocket.close();
  364. return this._state;
  365. }
  366. }
  367. checkHeartBeat()
  368. {
  369. var self = this;
  370. // if(this._bClientClosed = true)
  371. // {
  372. // return
  373. // }
  374. self._timeOut = setTimeout(function () {
  375. if(self._bNeedClose != true)
  376. {
  377. if (self.pingTimes >= 3) //6次没有收到ping消息,认为断了线
  378. {
  379. Common.Print('pingTimes >= 3');
  380. self.pingTimes = 0;
  381. self.open(true);//认为已经断开连接//然后重连
  382. return;
  383. }
  384. //记录心跳次数
  385. self.pingTimes++;
  386. self.sendPing();
  387. }
  388. self.checkHeartBeat();
  389. }, this._heatInterval);
  390. }
  391. sendPing()
  392. {
  393. console.log(Common.GetDateString() + 'sendPing');
  394. var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_KN_COMMAND ,ConstMsgId.SUB_KN_DETECT_SOCKET,4 + 4 )
  395. var sre = "hert"
  396. console.log('msg is: ',sre);
  397. this.sendMsg(sre);
  398. }
  399. }