socket.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /**
  2. * 小程序 WebSocket 通讯封装参考
  3. */
  4. class ChatSocket {
  5. constructor(url) {
  6. this.url = url;
  7. this.socketTask = null;
  8. this.isOpen = false;
  9. this.reconnectCount = 0;
  10. this.maxReconnect = 5;
  11. this.timer = null;
  12. this.onMessageCallback = null;
  13. }
  14. // 初始化连接
  15. connect(token) {
  16. if (this.isOpen) return;
  17. this.socketTask = uni.connectSocket({
  18. url: `${this.url}?token=${token}`,
  19. success: () => {
  20. console.log('WebSocket 连接发起成功');
  21. }
  22. });
  23. this.socketTask.onOpen(() => {
  24. console.log('WebSocket 已连接');
  25. this.isOpen = true;
  26. this.reconnectCount = 0;
  27. this.startHeartbeat();
  28. });
  29. this.socketTask.onMessage((res) => {
  30. const data = JSON.parse(res.data);
  31. if (this.onMessageCallback) {
  32. this.onMessageCallback(data);
  33. }
  34. });
  35. this.socketTask.onClose(() => {
  36. console.log('WebSocket 已关闭');
  37. this.isOpen = false;
  38. this.reconnect();
  39. });
  40. this.socketTask.onError((err) => {
  41. console.error('WebSocket 错误', err);
  42. this.isOpen = false;
  43. });
  44. }
  45. // 发送消息
  46. send(msgObj) {
  47. if (!this.isOpen) {
  48. console.error('连接未建立,消息发送失败');
  49. return;
  50. }
  51. this.socketTask.send({
  52. data: JSON.stringify(msgObj),
  53. success: () => {
  54. console.log('消息已发出', msgObj);
  55. }
  56. });
  57. }
  58. // 心跳机制
  59. startHeartbeat() {
  60. this.timer = setInterval(() => {
  61. if (this.isOpen) {
  62. this.send({ type: 'heartbeat', msg: 'ping' });
  63. }
  64. }, 30000);
  65. }
  66. // 监听消息
  67. onMessage(callback) {
  68. this.onMessageCallback = callback;
  69. }
  70. // 断线重连
  71. reconnect() {
  72. if (this.reconnectCount < this.maxReconnect) {
  73. this.reconnectCount++;
  74. setTimeout(() => {
  75. console.log(`正在进行第 ${this.reconnectCount} 次重连...`);
  76. this.connect();
  77. }, 3000 * this.reconnectCount);
  78. }
  79. }
  80. close() {
  81. if (this.socketTask) {
  82. this.socketTask.close();
  83. clearInterval(this.timer);
  84. }
  85. }
  86. }
  87. export default new ChatSocket('wss://your-api.com/ws/chat');