socket.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import { defineStore } from "pinia";
  2. import verConfig from "@/ver.config";
  3. import { Toast } from "@/utils";
  4. import { useUserStore } from "./user";
  5. const state = () => ({
  6. socket: null,
  7. heartBeatInterval: null,
  8. connectNum: 1,
  9. timeout: 30000,
  10. heartbeatInterval: null,
  11. reconnectTimeOut: null,
  12. is_open_socket: false,
  13. traderDetailIndex: 100,
  14. accountStateIndex: 100,
  15. followFlake: false,
  16. init: false,
  17. networkStatus: true,
  18. socket_id: ''
  19. })
  20. export const useSocketStore = defineStore('socket', {
  21. state,
  22. getters: {
  23. socketId() {
  24. return this.socket_id;
  25. }
  26. },
  27. actions: {
  28. connect() {
  29. this.socket = uni.connectSocket({
  30. url: verConfig.wsUrl,
  31. success: () => { console.log("Connection successful") }
  32. })
  33. this.socket.onOpen(() => this.onOpen());
  34. this.socket.onMessage((res) => this.onMessage(res));
  35. this.socket.onClose(() => this.onClose());
  36. },
  37. CALLBACK(res) {
  38. if (res.isConnected) {
  39. this.traderDetailIndex = 2;
  40. this.connect()
  41. }
  42. },
  43. send(_data) {
  44. if (this.socket) {
  45. this.socket.send({
  46. data: JSON.stringify(_data),
  47. async success() { },
  48. });
  49. }
  50. },
  51. onOpen(event) {
  52. uni.$emit('socketStatus', true);
  53. if (!this.networkStatus) {
  54. uni.offNetworkStatusChange(this.CALLBACK);
  55. }
  56. this.networkStatus = true;
  57. this.connectNum = 1;
  58. // this.send({ "event": "pusher:subscribe", "data": { "auth": "", "channel": "chat" } });
  59. clearInterval(this.reconnectTimeOut)
  60. clearInterval(this.heartbeatInterval)
  61. this.is_open_socket = true;
  62. this.start();
  63. },
  64. onMessage(res) {
  65. const useUser = useUserStore();
  66. const messageData = JSON.parse(res.data || '{}');
  67. const message = (messageData.data && messageData.data != '{}') ? JSON.parse(messageData.data) : {};
  68. if (Object.keys(message).length && messageData.event != 'pusher:connection_established') { uni.$emit('$onMessage', { event: messageData.event, channel: messageData.channel || '', data: message }) }
  69. if (messageData.event === 'pusher:connection_established') {
  70. this.timeout = Number(message.activity_timeout) * 1000;
  71. this.socket_id = message.socket_id;
  72. if (useUser.getuserInfo.id && message.socket_id) return useUser.setAuth({ id: useUser.getuserInfo.id, socket_id: message.socket_id });
  73. }
  74. },
  75. onClose() {
  76. clearInterval(this.heartbeatInterval)
  77. clearInterval(this.reconnectTimeOut)
  78. this.is_open_socket = false;
  79. this.socket = null
  80. if (this.connectNum < 6) {
  81. this.reconnect();
  82. } else {
  83. uni.$emit('connectError');
  84. this.networkStatus = false;
  85. uni.onNetworkStatusChange(this.CALLBACK);
  86. this.connectNum = 1
  87. }
  88. },
  89. checkStatus() {
  90. console.log("检查状态")
  91. clearInterval(this.reconnectTimeOut)
  92. const { readyState } = this.socket
  93. if (!this.socket || [2, 3].includes(readyState)) {
  94. console.log("未链接!")
  95. return false;
  96. }
  97. return true;
  98. },
  99. start() {
  100. this.heartbeatInterval = setInterval(() => {
  101. this.send({ "event": "pusher:ping", "data": {} });
  102. }, this.timeout)
  103. },
  104. reconnect() {
  105. clearInterval(this.heartbeatInterval)
  106. if (!this.is_open_socket && (this.traderDetailIndex == 2 || this.accountStateIndex == 0 || this
  107. .followFlake)) {
  108. console.log("5秒后重新连接...")
  109. this.reconnectTimeOut = setInterval(() => {
  110. this.connect();
  111. }, 5000)
  112. }
  113. },
  114. closeScoket() {
  115. if (!this.is_open_socket) return;
  116. this.socket.close({
  117. success() { Toast('Scoket 关闭成功') }
  118. });
  119. },
  120. setSate(_state = {}) {
  121. let keys = Object.keys(_state);
  122. if (keys.length) {
  123. this[keys[0]] = _state[keys[0]]
  124. }
  125. }
  126. }
  127. })