吉安感知网项目-前端
罗广辉
2026-01-26 beb95fb5fc166804056abafd70fc01ac27de7621
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { useGlobalWS } from "@/hooks/useGlobalWS.js";// WebSocket服务管理
class WebSocketService {
  constructor() {
    this.socketTask = null
    this.connected = false
    this.url = ''
    this.userId = ''
    this.onMessageCallback = null
    this.onOpenCallback = null
    this.onCloseCallback = null
    this.onErrorCallback = null
    this.pingTimer = null
  }
 
  // 初始化WebSocket连接
  init(userId, url) {
    if (!url) {
      console.error('WebSocket初始化失败:缺少url')
      return
    }
 
    this.userId = userId || ''
    this.url = url + encodeURIComponent(this.userId)
    this.connect()
  }
 
  // 建立WebSocket连接
  connect() {
    try {
      // 关闭现有连接
      this.close()
 
      // 使用uni-app的WebSocket API
      this.socketTask = uni.connectSocket({
        url: this.url,
        success: () => {
          // console.log('WebSocket连接已请求')
        },
        fail: (error) => {
          // console.error('WebSocket连接请求失败:', error)
          if (this.onErrorCallback) {
            this.onErrorCallback(error)
          }
        }
      })
 
      // 监听连接打开
      this.socketTask.onOpen(() => {
        this.connected = true
        // console.log('WebSocket已连接,userId:', this.userId)
        this.startPing()
        if (this.onOpenCallback) {
          this.onOpenCallback()
        }
      })
 
      // 监听连接关闭
      this.socketTask.onClose(() => {
        this.connected = false
        // console.log('WebSocket已关闭')
        this.stopPing()
        if (this.onCloseCallback) {
          this.onCloseCallback()
        }
      })
 
      // 监听连接错误
      this.socketTask.onError((error) => {
        // console.error('WebSocket错误:', error)
        this.connected = false
        this.stopPing()
        if (this.onErrorCallback) {
          this.onErrorCallback(error)
        }
      })
 
      // 监听消息
      this.socketTask.onMessage((res) => {
        try {
          const message = JSON.parse(res.data)
          // console.log('收到WebSocket消息:', message)
          if (this.onMessageCallback) {
            this.onMessageCallback(message)
          }
        } catch (error) {
          // console.error('解析WebSocket消息失败:', error)
        }
      })
    } catch (error) {
      // console.error('WebSocket连接失败:', error)
      if (this.onErrorCallback) {
        this.onErrorCallback(error)
      }
    }
  }
 
  // 发送消息
  send(type, to, payload) {
    if (!type || !this.socketTask || !this.connected) {
      console.error('WebSocket发送失败:连接未建立')
      return
    }
 
    const message = {
      type,
      from: String(this.userId),
      to: String(to),
      payload: payload || null,
      timestamp: Date.now()
    }
 
    this.socketTask.send({
      data: JSON.stringify(message),
      success: () => {
        // console.log('WebSocket消息发送成功:', message)
        useGlobalWS();
      },
      fail: (error) => {
        // console.error('WebSocket消息发送失败:', error)
      }
    })
  }
 
  // 开始心跳检测
  startPing() {
    this.stopPing()
    // 每25秒发送一次心跳
    this.pingTimer = setInterval(() => {
      if (this.connected) {
        this.send('ping', 'system')
      }
    }, 25000)
  }
 
  // 停止心跳检测
  stopPing() {
    if (this.pingTimer) {
      clearInterval(this.pingTimer)
      this.pingTimer = null
    }
  }
 
  // 关闭连接
  close() {
    if (this.socketTask) {
      this.socketTask.close({
        code: 1000,
        reason: '正常关闭',
        success: () => {
          // console.log('WebSocket已关闭')
        },
        fail: (error) => {
          // console.error('WebSocket关闭失败:', error)
        }
      })
      this.socketTask = null
    }
    this.stopPing()
    this.connected = false
  }
 
  // 设置消息回调
  setOnMessageCallback(callback) {
    this.onMessageCallback = callback
  }
 
  // 获取当前消息回调(用于检查是否已设置)
  getOnMessageCallback() {
    return this.onMessageCallback
  }
 
  // 设置连接打开回调
  setOnOpenCallback(callback) {
    this.onOpenCallback = callback
  }
 
  // 设置连接关闭回调
  setOnCloseCallback(callback) {
    this.onCloseCallback = callback
  }
 
  // 设置错误回调
  setOnErrorCallback(callback) {
    this.onErrorCallback = callback
  }
 
  // 获取连接状态
  getConnected() {
    return this.connected
  }
}
 
// 导出单例实例
export default new WebSocketService()