gameSocket.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import { _decorator, Component, Node } from 'cc';
  2. import { msgManager } from './msgManager';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('gameSocket')
  5. export class gameSocket extends Component {
  6. private static _instance: gameSocket | null = null;
  7. public static get Instance() {
  8. if (gameSocket._instance === null)
  9. gameSocket._instance = new gameSocket();
  10. return gameSocket._instance;
  11. }
  12. sock:WebSocket = null;
  13. private current_url:string = '' //当前url
  14. is_connected:Boolean = false;
  15. stopConnected:Boolean = false;
  16. check_heartbeat_succeed:boolean = false;
  17. is_online_status:boolean = false; //是否是在线状态
  18. private reconnectInterval = 1000; // 重连间隔时间(毫秒)
  19. private reconnectMaxAttempts = 30; // 最大重连尝试次数
  20. private reconnectAttempts = 0; // 当前重连尝试次数
  21. private static RECV_HEART_BEAT ='1' //收到服务器心跳结果
  22. private static RECV_CHEAK_HEART_BEAT = '2' //服务器查询我的心跳
  23. _on_opened(event:Event):void {
  24. console.log('_on_opened=',event)
  25. this.reconnectAttempts = 0
  26. if(this.is_connected===true){
  27. }else{
  28. this.is_connected = true;
  29. this.check_heartbeat_succeed = true;
  30. gameSocket.Instance.is_online_status = true;
  31. // if(userDataManager.user_data!=null){
  32. // msgManager.relink()
  33. // }else{
  34. // }
  35. }
  36. }
  37. _on_recv_data(event:any):void {
  38. console.log('_on_recv_data=',event)
  39. this.check_heartbeat_succeed = true;
  40. if(event.data===gameSocket.RECV_HEART_BEAT){
  41. // if(GameMng.reward_tong_bi){
  42. // UIManager.removeWaitViewLayer()
  43. // GameMng.reward_tong_bi = false;
  44. // msgManager.ad_tongbi(1)
  45. // }
  46. // if(GameMng.firendOpenId!=""){
  47. // UIManager.removeWaitViewLayer()
  48. // msgManager.add_firend(parseInt(GameMng.firendOpenId))
  49. // msgManager.user_join_room(parseInt(GameMng.firendOpenId))
  50. // GameMng.firendOpenId = ""
  51. // }
  52. //console.log("接受服务端返回的心跳",GameUtil.curTime())
  53. return
  54. }
  55. if(event.data===gameSocket.RECV_CHEAK_HEART_BEAT){
  56. gameSocket.Instance.heartbeat();
  57. return
  58. }
  59. if(event.data===""||event.data===null){
  60. console.assert(true,"接受输出格式错误,data为空",event)
  61. }else{
  62. msgManager.recv(event.data)
  63. }
  64. }
  65. _on_socket_close(event:any):void {
  66. console.log("_on_socket_close",event)
  67. this.reConnectOperation()
  68. this.is_connected = false;
  69. }
  70. _on_socket_err(event:any):void {
  71. console.log("_on_socket_err",event)
  72. this.reConnectOperation()
  73. this.is_connected = false;
  74. }
  75. private reConnectOperation() {
  76. if (this.reconnectAttempts < this.reconnectMaxAttempts) {
  77. console.log('正在尝试重连...');
  78. setTimeout(()=>{
  79. this.reonnect()
  80. },this.reconnectInterval)
  81. this.reconnectAttempts++;
  82. } else {
  83. console.log('重连尝试次数已达上限');
  84. }
  85. }
  86. reonnect() {
  87. if(this.current_url.length<=0) {
  88. return
  89. }
  90. this.connect(this.current_url)
  91. }
  92. connect(url:any):void {
  93. if(this.stopConnected){
  94. console.log("客户端退出链接,暂不提供重连")
  95. return
  96. }
  97. this.current_url = url
  98. if(!this.is_connected){
  99. try{
  100. this.sock = new WebSocket(url);
  101. this.sock.binaryType = "arraybuffer"; //"arraybuffer", "blob", "document", "json", and "text".
  102. this.sock.onopen = this._on_opened.bind(this);
  103. this.sock.onmessage = this._on_recv_data.bind(this);
  104. this.sock.onclose = this._on_socket_close.bind(this);
  105. this.sock.onerror = this._on_socket_err.bind(this);
  106. }catch(e:any){
  107. console.log("connect error",e)
  108. }
  109. }
  110. }
  111. heartbeat(){
  112. this.check_heartbeat_succeed = false;
  113. this.send_cmd(0);
  114. }
  115. /**
  116. * this.sock.readyState
  117. * CONNECTING:值为0,表示正在连接
  118. * OPEN:值为1,表示连接成功,可以通信了
  119. * CLOSING:值为2,表示连接正在关闭
  120. * CLOSED:值为3,表示连接已经关闭,或者打开连接失败
  121. */
  122. send_cmd(body):void {
  123. if (!this.sock || !this.is_connected) {
  124. return;
  125. }
  126. try{
  127. console.log('sock.readyState=',this.sock.readyState)
  128. if(this.sock.readyState===1){
  129. if(typeof body == 'number'){
  130. body=body+""
  131. }
  132. console.log('发送消息',body)
  133. this.sock.send(body);
  134. }
  135. }catch(e:any){
  136. console.log("e",e)
  137. }
  138. }
  139. close():void {
  140. if (this.sock !== null) {
  141. this.sock.close();
  142. this.sock = null;
  143. }
  144. this.is_connected = false;
  145. this.check_heartbeat_succeed = false;
  146. }
  147. }