scoket.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. class socketIO {
  2. constructor(data, time, url, heartbeat) {
  3. this.socketTask = null;
  4. this.is_open_socket = false; //避免重复连接
  5. this.heartbeat = heartbeat ? heartbeat : 0;
  6. this.url = url;
  7. this.data = data ? data : null;
  8. this.connectNum = 10; // 重连次数
  9. this.traderDetailIndex = 100; // traderDetailIndex ==2 重连
  10. this.accountStateIndex = 100; // accountStateIndex ==1 重连
  11. this.followFlake = true; // followFlake == true 重连
  12. //心跳检测
  13. this.timeout = time ? time : 58000; //多少秒执行检测
  14. this.heartbeatInterval = null; //检测服务器端是否还活着
  15. this.reconnectTimeOut = null; //重连之后多久再次重连
  16. }
  17. // 进入这个页面的时候创建websocket连接【整个页面随时使用】
  18. connectSocketInit(data) {
  19. this.data = data;
  20. this.socketTask = uni.connectSocket({
  21. url: this.url,
  22. success: () => {
  23. console.log('正准备建立websocket中...');
  24. // 返回实例
  25. return this.socketTask;
  26. }
  27. });
  28. this.socketTask.onOpen((res) => {
  29. this.connectNum = 1;
  30. console.log('WebSocket连接正常!');
  31. this.send(data);
  32. clearInterval(this.reconnectTimeOut);
  33. clearInterval(this.heartbeatInterval);
  34. this.is_open_socket = true;
  35. this.start();
  36. // 注:只有连接正常打开中 ,才能正常收到消息
  37. this.socketTask.onMessage((e) => {
  38. // 字符串转json
  39. let res = e.data;
  40. console.log('res---------->', res); // 这里 查看 推送过来的消息
  41. if (res) {
  42. uni.$emit('getPositonsOrder', res);
  43. }
  44. });
  45. });
  46. // 监听连接失败,这里代码我注释掉的原因是因为如果服务器关闭后,和下面的onclose方法一起发起重连操作,这样会导致重复连接
  47. uni.onSocketError((res) => {
  48. console.log('WebSocket连接打开失败,请检查!');
  49. this.socketTask = null;
  50. this.is_open_socket = false;
  51. clearInterval(this.heartbeatInterval);
  52. clearInterval(this.reconnectTimeOut);
  53. // uni.$off('getPositonsOrder');
  54. if (this.connectNum < 6) {
  55. uni.showToast({
  56. title: `WebSocket连接失败,正尝试第${this.connectNum}次连接`,
  57. icon: 'none'
  58. });
  59. this.reconnect();
  60. this.connectNum += 1;
  61. } else {
  62. uni.$emit('connectError');
  63. this.connectNum = 1;
  64. }
  65. });
  66. // 这里仅是事件监听【如果socket关闭了会执行】
  67. this.socketTask.onClose(() => {
  68. console.log('已经被关闭了-------');
  69. clearInterval(this.heartbeatInterval);
  70. clearInterval(this.reconnectTimeOut);
  71. this.is_open_socket = false;
  72. this.socketTask = null;
  73. // uni.$off('getPositonsOrder');
  74. if (this.connectNum < 6) {
  75. console.log('执行重连了', this.connectNum);
  76. this.reconnect();
  77. } else {
  78. console.log('没执行重连了', this.connectNum);
  79. uni.$emit('connectError');
  80. uni.$off('getPositonsOrder');
  81. this.connectNum = 1;
  82. }
  83. });
  84. }
  85. // 主动关闭socket连接
  86. Close() {
  87. if (!this.is_open_socket) {
  88. return;
  89. }
  90. this.socketTask.close({
  91. success() {
  92. // uni.showToast({
  93. // title: 'SocketTask 关闭成功',
  94. // icon: 'none'
  95. // });
  96. }
  97. });
  98. }
  99. //发送消息
  100. send(data) {
  101. console.log('data---------->', data, typeof data);
  102. // 注:只有连接正常打开中 ,才能正常成功发送消息
  103. if (this.socketTask) {
  104. this.socketTask.send({
  105. data: typeof data === 'object' ? JSON.stringify(data) : data,
  106. async success() {
  107. console.log('消息发送成功');
  108. }
  109. });
  110. }
  111. }
  112. //开启心跳检测
  113. start() {
  114. this.heartbeatInterval = setInterval(() => {
  115. this.send(this.heartbeat ? this.heartbeat : 0);
  116. }, this.timeout);
  117. }
  118. //重新连接
  119. reconnect() {
  120. //停止发送心跳
  121. clearInterval(this.heartbeatInterval);
  122. //如果不是人为关闭的话,进行重连
  123. if (!this.is_open_socket && (this.traderDetailIndex == 2 || this.accountStateIndex == 0 || this.followFlake)) {
  124. this.reconnectTimeOut = setInterval(() => {
  125. this.connectSocketInit(this.data);
  126. console.log('触发重连');
  127. }, 5000);
  128. }
  129. }
  130. /**
  131. * @description 将 scoket 数据进行过滤
  132. * @param {array} array
  133. * @param {string} type 区分 弹窗 openposition 分为跟随和我的
  134. */
  135. arrayFilter(array, type = 'normal', signalId = 0) {
  136. let arr1 = [];
  137. let arr2 = [];
  138. let obj = {
  139. arr1: [],
  140. arr2: []
  141. };
  142. arr1 = array.filter((v) => v.flwsig == true);
  143. arr2 = array.filter((v) => v.flwsig == false);
  144. if (type == 'normal') {
  145. if (signalId) {
  146. arr1 = array.filter((v) => v.flwsig == true && v.sigtraderid == signalId);
  147. return arr1;
  148. } else {
  149. return arr1.concat(arr2);
  150. }
  151. } else {
  152. if (signalId > 0) {
  153. arr1 = array.filter((v) => v.flwsig == true && v.sigtraderid == signalId);
  154. obj.arr1 = arr1;
  155. } else {
  156. obj.arr1 = arr1;
  157. }
  158. obj.arr2 = arr2;
  159. return obj;
  160. }
  161. }
  162. }
  163. module.exports = socketIO;