websocket.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. // utils/websocket.js
  2. class LocalWebSocket {
  3. constructor() {
  4. this.socket = null;
  5. this.isConnected = false;
  6. this.reconnectTimer = null;
  7. this.reconnectCount = 0;
  8. this.maxReconnectAttempts = 5;
  9. this.reconnectDelay = 3000;
  10. // 默认配置
  11. this.defaultConfig = {
  12. ip: '192.168.1.100',
  13. port: 8080,
  14. path: '/websocket'
  15. };
  16. this.storageKey = 'WEBSOCKET_SERVER_CONFIG';
  17. }
  18. // 从本地存储获取配置
  19. getConfig() {
  20. try {
  21. const configStr = uni.getStorageSync(this.storageKey);
  22. if (configStr) {
  23. return JSON.parse(configStr);
  24. }
  25. return this.defaultConfig;
  26. } catch (error) {
  27. console.error('获取WebSocket配置失败:', error);
  28. return this.defaultConfig;
  29. }
  30. }
  31. // 保存配置到本地存储
  32. saveConfig(config) {
  33. try {
  34. uni.setStorageSync(this.storageKey, JSON.stringify(config));
  35. return true;
  36. } catch (error) {
  37. console.error('保存WebSocket配置失败:', error);
  38. return false;
  39. }
  40. }
  41. // 获取WebSocket连接URL
  42. getWebSocketURL() {
  43. const config = this.getConfig();
  44. return `ws://${config.ip}:${config.port}${config.path}`;
  45. }
  46. // 连接WebSocket
  47. connect() {
  48. if (this.socket && this.isConnected) {
  49. console.log('WebSocket已连接');
  50. return;
  51. }
  52. const url = this.getWebSocketURL();
  53. console.log('尝试连接WebSocket:', url);
  54. // 创建WebSocket连接
  55. this.socket = new WebSocket(url);
  56. // 监听连接成功
  57. this.socket.onopen = (event) => {
  58. console.log('WebSocket连接成功');
  59. this.isConnected = true;
  60. this.reconnectCount = 0;
  61. this.onOpen && this.onOpen(event);
  62. };
  63. // 监听消息接收
  64. this.socket.onmessage = (event) => {
  65. console.log('收到WebSocket消息:', event.data);
  66. this.onMessage && this.onMessage(event);
  67. };
  68. // 监听连接关闭
  69. this.socket.onclose = (event) => {
  70. console.log('WebSocket连接关闭:', event);
  71. this.isConnected = false;
  72. this.onClose && this.onClose(event);
  73. this.handleReconnect();
  74. };
  75. // 监听错误
  76. this.socket.onerror = (error) => {
  77. console.error('WebSocket连接错误:', error);
  78. this.onError && this.onError(error);
  79. };
  80. }
  81. // 处理重连
  82. handleReconnect() {
  83. if (this.reconnectCount < this.maxReconnectAttempts) {
  84. this.reconnectCount++;
  85. console.log(`WebSocket尝试重连 (${this.reconnectCount}/${this.maxReconnectAttempts})`);
  86. this.reconnectTimer = setTimeout(() => {
  87. this.connect();
  88. }, this.reconnectDelay * this.reconnectCount);
  89. } else {
  90. console.log('WebSocket重连次数已达上限');
  91. }
  92. }
  93. // 发送消息
  94. send(data) {
  95. if (this.isConnected && this.socket) {
  96. if (typeof data === 'object') {
  97. data = JSON.stringify(data);
  98. }
  99. this.socket.send(data);
  100. return true;
  101. } else {
  102. console.warn('WebSocket未连接,无法发送消息');
  103. return false;
  104. }
  105. }
  106. // 关闭连接
  107. close() {
  108. if (this.socket) {
  109. this.socket.close();
  110. this.socket = null;
  111. }
  112. if (this.reconnectTimer) {
  113. clearTimeout(this.reconnectTimer);
  114. this.reconnectTimer = null;
  115. }
  116. this.isConnected = false;
  117. }
  118. // 更新服务端配置
  119. updateServerConfig(newConfig) {
  120. const config = { ...this.defaultConfig, ...newConfig };
  121. this.saveConfig(config);
  122. // 如果当前已连接,重新连接
  123. if (this.isConnected) {
  124. this.close();
  125. this.connect();
  126. }
  127. }
  128. // 设置回调函数
  129. setOnOpen(callback) {
  130. this.onOpen = callback;
  131. }
  132. setOnMessage(callback) {
  133. this.onMessage = callback;
  134. }
  135. setOnClose(callback) {
  136. this.onClose = callback;
  137. }
  138. setOnError(callback) {
  139. this.onError = callback;
  140. }
  141. }
  142. export default new LocalWebSocket();