websocket.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. // websocket.js
  2. let socketTask = null;
  3. let reconnectAttempts = 0;
  4. const maxReconnectAttempts = 5;
  5. let heartbeatTimer = null;
  6. export function connectWebSocket() {
  7. return new Promise((resolve, reject) => {
  8. const token = uni.getStorageSync('Access-Token');
  9. const Ids = uni.getStorageSync('login_user_info')['id'];
  10. const userId = Ids + '_app?token=' + token;
  11. // const url = 'http://' + window.location.hostname + ':9999'?.replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId;
  12. const url = uni.getStorageSync("apiUrl").replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId;
  13. console.log(url, 'url======')
  14. // 创建连接
  15. socketTask = uni.connectSocket({
  16. url: url,
  17. success: () => {
  18. console.log('WebSocket 连接创建中...');
  19. },
  20. fail: (err) => {
  21. console.error('连接创建失败:', err);
  22. reject(err);
  23. }
  24. });
  25. // 监听打开事件
  26. socketTask.onOpen((res) => {
  27. console.log('WebSocket 连接已打开');
  28. startHeartbeat();
  29. reconnectAttempts = 0;
  30. resolve(socketTask);
  31. });
  32. // 监听错误事件
  33. socketTask.onError((err) => {
  34. console.error('WebSocket 错误:', err);
  35. handleReconnection();
  36. reject(err);
  37. });
  38. // 监听关闭事件
  39. socketTask.onClose((res) => {
  40. console.log('WebSocket 连接已关闭', res);
  41. clearInterval(heartbeatTimer);
  42. if (!res.code === 1000) { // 非正常关闭
  43. handleReconnection();
  44. }
  45. });
  46. });
  47. }
  48. function handleReconnection() {
  49. if (reconnectAttempts < maxReconnectAttempts) {
  50. reconnectAttempts++;
  51. const delay = Math.min(1000 * reconnectAttempts, 5000);
  52. console.log(`尝试第 ${reconnectAttempts} 次重连,${delay}ms后执行`);
  53. setTimeout(() => {
  54. connectWebSocket().catch(console.error);
  55. }, delay);
  56. } else {
  57. console.error(`已达到最大重连次数 ${maxReconnectAttempts}`);
  58. }
  59. }
  60. // 发送消息
  61. export function sendWebSocketMessage(message) {
  62. return new Promise((resolve, reject) => {
  63. if (!socketTask || socketTask.readyState !== 1) {
  64. reject('WebSocket 未连接');
  65. return;
  66. }
  67. socketTask.send({
  68. data: JSON.stringify(message),
  69. success: () => resolve(),
  70. fail: (err) => reject(err)
  71. });
  72. });
  73. }
  74. // 关闭连接
  75. export function closeWebSocket() {
  76. if (socketTask) {
  77. socketTask.close({
  78. code: 1000,
  79. reason: '用户主动关闭'
  80. });
  81. }
  82. }
  83. function startHeartbeat() {
  84. // 每30秒发送一次心跳
  85. heartbeatTimer = setInterval(() => {
  86. sendWebSocketMessage({
  87. type: 'heartbeat',
  88. timestamp: Date.now()
  89. }).catch(() => {
  90. clearInterval(heartbeatTimer);
  91. });
  92. }, 3*60000);
  93. }