NetManager.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { FrameworkConf } from "../../framework/config/FrameworkConf";
  2. import { Framework } from "../../framework/Framework";
  3. import { UserData } from "../data/UserData";
  4. import { GameEvent } from "../data/GameEvent";
  5. import { StringUtil } from "../../framework/util/StringUtil";
  6. import { ViewID } from "../../framework/config/LayerConf";
  7. export class NetManager {
  8. private _socket: WebSocket = null;
  9. private _web_url = ""; //服务器地址
  10. private _callback: Function = null;
  11. private _hear_time = 5; //心跳时间
  12. private _hear_time_out = 2; //心跳超次数()
  13. private _hear_time_cur = 0; //心跳超时次数
  14. private _hear_uuid = 0; //心跳定时器
  15. private _is_connect = false; //网络是否连接
  16. private _bReconnect = false; //是否重连
  17. private _bHandShake = false; //是否握手
  18. private _bProClose = false; //是否主动断开
  19. private _uid = 0;
  20. private _seq = 0;
  21. //心跳超时 自动重连,超过5次则不再重连
  22. private _auto_reconnect_time = 0;
  23. private _auto_reconnect_time_out = 5;
  24. private _socketId = 0;
  25. //网络是否连接
  26. get is_connect() {
  27. return this._is_connect;
  28. }
  29. get is_handShake() {
  30. return this._bHandShake;
  31. }
  32. get bReconnect() {
  33. return this._bReconnect;
  34. }
  35. get bProClose() {
  36. return this._bProClose;
  37. }
  38. connect(url: string, callback: Function) {
  39. //this.close(false);
  40. let socketId = ++this._socketId
  41. this._clearHeart();
  42. this._web_url = url;
  43. this._callback = callback;
  44. this._socket = new WebSocket(this._web_url, 'default-protocol');
  45. this._socket.binaryType = "arraybuffer";
  46. this._socket.onopen = (event: any) => {
  47. if(socketId != this._socketId){
  48. return
  49. }
  50. callback && callback(0);
  51. callback = null;
  52. this._is_connect = true;
  53. this._bProClose = false
  54. this._auto_reconnect_time = 0
  55. this._hear_time_cur = 0
  56. };
  57. this._socket.onerror = (event: any) => {
  58. if(socketId != this._socketId){
  59. return
  60. }
  61. console.log("onerror:", event," socketId:",socketId);
  62. callback && callback(1);
  63. callback = null;
  64. this._is_connect = false;
  65. this._bHandShake = false
  66. this._clearHeart();
  67. // this._socket = null
  68. // this._autoReconnect(3)
  69. Framework.event.fireEvent(FrameworkConf.Event.NET_ERROR, event);
  70. };
  71. this._socket.onclose = (event: any) => {
  72. if(socketId != this._socketId){
  73. return
  74. }
  75. console.log("onclose1:", event," socketId:",socketId);
  76. this._is_connect = false;
  77. this._bHandShake = false
  78. this._bReconnect = false
  79. this._clearHeart();
  80. this._socket = null
  81. Framework.layer.open(ViewID.MaskUI,()=>{});
  82. if(!this._bProClose){
  83. this._autoReconnect(3)
  84. }
  85. else Framework.event.fireEvent(FrameworkConf.Event.NET_CLOSE, event);
  86. };
  87. this._socket.onmessage = (event: any) => {
  88. let Json = JSON.parse(event.data)
  89. // console.log(Json);
  90. if (Json.mod == 'user' && Json.act == 'handshake') {
  91. this._startHeart();
  92. if (Json.code == 0) {
  93. Framework.layer.close(ViewID.MaskUI);
  94. this._bHandShake = true
  95. // if(Framework.layer.getUIView(ViewID.BombUI)){
  96. //window.parent.postMessage(FrameworkConf.Event.NET_RECONNECT, "*");
  97. this._uid = Json.data._id
  98. Framework.event.fireEvent(FrameworkConf.Event.NET_RECONNECT, {});
  99. this._bReconnect = false
  100. //}
  101. // if(!Framework.layer.getUIView(ViewID.BombUI)){
  102. // var args = { 'uid': Json.data._id, 'cash': Json.data.cash, 'state': 1 };
  103. // Framework.layer.open(ViewID.BombUI, null, args);
  104. // }
  105. }else {
  106. this.close(false)
  107. Framework.event.fireEvent(FrameworkConf.Event.NET_HANDSHAKE_ERROR, Json.code);
  108. // 弹窗提示登陆失败
  109. Framework.tips.setTips(Json.desc);
  110. }
  111. }else if (Json.mod == 'user' && Json.act == 'heart_beat') {
  112. this._hear_time_cur = 0;
  113. //console.error(Json)
  114. } else {
  115. if (Json.seq == this._seq) {
  116. // 解开遮罩
  117. }
  118. // console.log("onmessage:",event.data);
  119. Framework.event.fireEvent(FrameworkConf.Event.NET_MSG, Json);
  120. }
  121. };
  122. }
  123. /**
  124. * 关闭socket
  125. * @param bReconnect 是否重连
  126. */
  127. close(bReconnect) {
  128. console.log("close test");
  129. this._socket && this._socket.close();
  130. this._socket = null;
  131. this._is_connect = false;
  132. this._bHandShake = false
  133. this._bProClose = true;
  134. this._clearHeart();
  135. // window.parent.postMessage(FrameworkConf.Event.NET_CLOSE, "*");
  136. if(bReconnect){
  137. Framework.layer.open(ViewID.MaskUI);
  138. this._autoReconnect()
  139. }
  140. else{
  141. Framework.layer.open(ViewID.MaskUI,()=>{},{closeTime:0});
  142. console.error("断开连接")
  143. }
  144. }
  145. send(msg: any) {
  146. //msg.uid = UserData['_id'];
  147. let msgStr = JSON.stringify(msg)
  148. // console.log(msgStr);
  149. // console.log(this._socket);
  150. if (this._socket) {
  151. // // let strBuf = this.protoEncode(cmd, msg);
  152. // // let buf = this.packet(strBuf);
  153. this._socket.send(msgStr)
  154. }
  155. }
  156. // uint8Array转typedArray
  157. typedArray(uint8Array) {
  158. var hex = Array.prototype.map
  159. .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
  160. .join('');
  161. var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
  162. return parseInt(h, 16)
  163. }))
  164. var buffer = typedArray.buffer;
  165. return buffer;
  166. }
  167. private _clearHeart() {
  168. (this._hear_uuid != 0) && Framework.time.unschedule(this._hear_uuid);
  169. this._hear_uuid = 0;
  170. }
  171. private _startHeart() {
  172. this._clearHeart();
  173. this._hear_uuid = Framework.time.schedule(() => {
  174. this._hear_time_cur += 1;
  175. if(this._hear_time_cur > this._hear_time_out){
  176. console.error("心跳超时",this._hear_time_cur);
  177. this.close(true);
  178. //this._autoReconnect()
  179. }
  180. else if (this._socket) {
  181. // this._hear_uuid = 0;
  182. this.netApiSend("user","heart_beat",{});
  183. }
  184. }, this._hear_time);
  185. }
  186. // 自动重连
  187. // delay:延迟时间
  188. private _autoReconnect(delay?:number) {
  189. if(this._bReconnect) {
  190. console.error("自动重连中",new Date());
  191. return
  192. }
  193. if (this._is_connect) {
  194. return;
  195. }
  196. if (this._auto_reconnect_time > this._auto_reconnect_time_out) {
  197. Framework.tips.setTips("Reconnection failed");
  198. console.error("多少次重连失败1")
  199. //window.parent.postMessage(FrameworkConf.Event.NET_ERROR, "*");
  200. Framework.layer.open(ViewID.MaskUI,()=>{},{closeTime:0});
  201. return;
  202. }
  203. delay = delay || 0
  204. if(delay > 0){
  205. Framework.time.scheduleOnce(()=>{
  206. this._autoReconnect()
  207. },delay)
  208. return
  209. }
  210. console.log("自动重连");
  211. this._auto_reconnect_time += 1;
  212. this._bReconnect = true
  213. this.connect(this._web_url,this._callback)
  214. }
  215. netApiSend(mod, act, args) {
  216. let req = {
  217. mod: mod,
  218. act: act,
  219. args: args,
  220. uid: this._uid,
  221. seq: this._seq++,
  222. }
  223. Framework.event.fireEvent('cid', args);
  224. // if(act != "heart_beat"){
  225. // console.log("发送", req);
  226. // }
  227. this.send(req);// 握手消息,返回在netmanger里面处理
  228. // 启动loading 遮罩id
  229. }
  230. }