committed by
trae-solo-agent
co-authored by
Kimi-K3.1-Pro noreply@anthropic.com
parent
d3f399d1ad
commit
d731fc1da3
+86
-110
@@ -1,11 +1,10 @@
|
||||
const WS_BASE_URL = 'wss://api.huashengtec.com/health-ws'
|
||||
//const WS_BASE_URL = 'ws://127.0.0.1:9005'
|
||||
// const WS_BASE_URL = 'ws://127.0.0.1:9005'
|
||||
|
||||
class AIChatSocket {
|
||||
constructor(url = `${WS_BASE_URL}/chat`, options = {}) {
|
||||
this.url = url
|
||||
this.options = {
|
||||
timeout: 10000,
|
||||
heartbeatInterval: 30000,
|
||||
autoReconnect: true,
|
||||
maxReconnectAttempts: 3,
|
||||
@@ -16,7 +15,7 @@ class AIChatSocket {
|
||||
this.socketTask = null
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
this.messageQueue = []
|
||||
this.connectPromise = null
|
||||
this.reconnectAttempts = 0
|
||||
|
||||
this._openCallback = null
|
||||
@@ -26,136 +25,124 @@ class AIChatSocket {
|
||||
this._heartbeatTimer = null
|
||||
}
|
||||
|
||||
// 连接 Promise 单飞:调用方必须 await 成功后再发送,避免断线后的首条消息竞态。
|
||||
connect() {
|
||||
if (this.isConnected || this.isConnecting) {
|
||||
console.log('[AIChatSocket] Already connected or connecting')
|
||||
return Promise.resolve()
|
||||
}
|
||||
if (this.isConnected) return Promise.resolve()
|
||||
if (this.connectPromise) return this.connectPromise
|
||||
|
||||
this.isConnecting = true
|
||||
this.connectPromise = new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
const succeed = () => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
this.isConnecting = false
|
||||
this.connectPromise = null
|
||||
resolve()
|
||||
}
|
||||
const fail = (err) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
this.isConnecting = false
|
||||
this.connectPromise = null
|
||||
reject(err instanceof Error ? err : new Error('WebSocket 连接失败'))
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
this.socketTask = wx.connectSocket({
|
||||
url: this.url,
|
||||
header: {
|
||||
'content-type': 'application/json',
|
||||
...this.options.header
|
||||
},
|
||||
protocols: this.options.protocols || [],
|
||||
success: () => {
|
||||
console.log('[AIChatSocket] WebSocket connecting...')
|
||||
},
|
||||
fail: (err) => {
|
||||
this.isConnecting = false
|
||||
console.error('[AIChatSocket] Connect failed:', err)
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
try {
|
||||
this.socketTask = wx.connectSocket({
|
||||
url: this.url,
|
||||
header: {
|
||||
'content-type': 'application/json',
|
||||
...this.options.header
|
||||
},
|
||||
protocols: this.options.protocols || [],
|
||||
fail
|
||||
})
|
||||
} catch (err) {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.socketTask) {
|
||||
this.isConnecting = false
|
||||
reject(new Error('SocketTask creation failed'))
|
||||
fail(new Error('SocketTask creation failed'))
|
||||
return
|
||||
}
|
||||
|
||||
this.socketTask.onOpen(() => {
|
||||
console.log('[AIChatSocket] Connection opened')
|
||||
this.isConnected = true
|
||||
this.isConnecting = false
|
||||
this.reconnectAttempts = 0
|
||||
this._startHeartbeat()
|
||||
|
||||
this._flushMessageQueue()
|
||||
|
||||
if (this._openCallback) {
|
||||
this._openCallback()
|
||||
}
|
||||
resolve()
|
||||
if (this._openCallback) this._openCallback()
|
||||
succeed()
|
||||
})
|
||||
|
||||
this.socketTask.onClose((res) => {
|
||||
console.log('[AIChatSocket] Connection closed:', res)
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
this._stopHeartbeat()
|
||||
|
||||
if (this._closeCallback) {
|
||||
this._closeCallback(res)
|
||||
}
|
||||
|
||||
fail(new Error(`WebSocket 已关闭:${res.code || 'unknown'}`))
|
||||
if (this._closeCallback) this._closeCallback(res)
|
||||
if (this.options.autoReconnect && this.reconnectAttempts < this.options.maxReconnectAttempts) {
|
||||
this._reconnect()
|
||||
}
|
||||
})
|
||||
|
||||
this.socketTask.onError((err) => {
|
||||
console.error('[AIChatSocket] WebSocket error:', err)
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
|
||||
if (this._errorCallback) {
|
||||
this._errorCallback(err)
|
||||
}
|
||||
if (this._errorCallback) this._errorCallback(err)
|
||||
fail(new Error(err?.errMsg || 'WebSocket 连接错误'))
|
||||
})
|
||||
|
||||
this.socketTask.onMessage((res) => {
|
||||
if (!this._messageCallback) return
|
||||
try {
|
||||
const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
|
||||
if (this._messageCallback) {
|
||||
this._messageCallback(data)
|
||||
}
|
||||
} catch (e) {
|
||||
if (this._messageCallback) {
|
||||
this._messageCallback(res.data)
|
||||
}
|
||||
this._messageCallback(data)
|
||||
} catch (err) {
|
||||
this._messageCallback({
|
||||
source: 'system',
|
||||
type: 'error',
|
||||
content: '收到无法解析的服务消息',
|
||||
id: ''
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
return this.connectPromise
|
||||
}
|
||||
|
||||
send(data) {
|
||||
const message = typeof data === 'string' ? data : JSON.stringify(data)
|
||||
|
||||
if (!this.isConnected || !this.socketTask) {
|
||||
console.log('[AIChatSocket] Not connected, queueing message')
|
||||
this.messageQueue.push(message)
|
||||
return false
|
||||
return Promise.reject(new Error('WebSocket 尚未连接'))
|
||||
}
|
||||
|
||||
try {
|
||||
this.socketTask.send({
|
||||
data: message,
|
||||
fail: (err) => {
|
||||
console.error('[AIChatSocket] Send failed:', err)
|
||||
this.messageQueue.push(message)
|
||||
}
|
||||
})
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('[AIChatSocket] Send error:', err)
|
||||
this.messageQueue.push(message)
|
||||
return false
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
this.socketTask.send({
|
||||
data: message,
|
||||
success: resolve,
|
||||
fail: (err) => reject(new Error(err?.errMsg || '消息发送失败'))
|
||||
})
|
||||
} catch (err) {
|
||||
reject(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
close() {
|
||||
this._stopHeartbeat()
|
||||
this.options.autoReconnect = false
|
||||
|
||||
if (this.socketTask) {
|
||||
this.socketTask.close({
|
||||
code: 1000,
|
||||
reason: 'User closed',
|
||||
fail: (err) => {
|
||||
console.error('[AIChatSocket] Close failed:', err)
|
||||
}
|
||||
})
|
||||
this.socketTask = null
|
||||
}
|
||||
|
||||
const task = this.socketTask
|
||||
this.socketTask = null
|
||||
this.isConnected = false
|
||||
this.isConnecting = false
|
||||
this.messageQueue = []
|
||||
if (task) {
|
||||
task.close({
|
||||
code: 1000,
|
||||
reason: 'User closed',
|
||||
fail: (err) => console.error('[AIChatSocket] Close failed:', err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
onOpen(callback) {
|
||||
@@ -174,21 +161,10 @@ class AIChatSocket {
|
||||
this._messageCallback = callback
|
||||
}
|
||||
|
||||
_flushMessageQueue() {
|
||||
if (this.messageQueue.length === 0) return
|
||||
|
||||
console.log(`[AIChatSocket] Flushing ${this.messageQueue.length} queued messages`)
|
||||
while (this.messageQueue.length > 0) {
|
||||
const message = this.messageQueue.shift()
|
||||
this.send(message)
|
||||
}
|
||||
}
|
||||
|
||||
_reconnect() {
|
||||
this.reconnectAttempts++
|
||||
console.log(`[AIChatSocket] Reconnecting... Attempt ${this.reconnectAttempts}/${this.options.maxReconnectAttempts}`)
|
||||
|
||||
setTimeout(() => {
|
||||
if (!this.options.autoReconnect || this.isConnected) return
|
||||
this.connect().catch((err) => {
|
||||
console.error('[AIChatSocket] Reconnect failed:', err)
|
||||
})
|
||||
@@ -197,17 +173,17 @@ class AIChatSocket {
|
||||
|
||||
_startHeartbeat() {
|
||||
this._stopHeartbeat()
|
||||
|
||||
this._heartbeatTimer = setInterval(() => {
|
||||
if (this.isConnected && this.socketTask) {
|
||||
this.socketTask.send({
|
||||
data: JSON.stringify({ type: 'ping' }),
|
||||
fail: (err) => {
|
||||
console.error('[AIChatSocket] Heartbeat failed:', err)
|
||||
this._stopHeartbeat()
|
||||
}
|
||||
})
|
||||
}
|
||||
if (!this.isConnected || !this.socketTask) return
|
||||
this.send({
|
||||
source: 'client',
|
||||
type: 'ping',
|
||||
content: '',
|
||||
id: `heartbeat_${Date.now()}`
|
||||
}).catch((err) => {
|
||||
console.error('[AIChatSocket] Heartbeat failed:', err)
|
||||
this._stopHeartbeat()
|
||||
})
|
||||
}, this.options.heartbeatInterval)
|
||||
}
|
||||
|
||||
@@ -219,4 +195,4 @@ class AIChatSocket {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AIChatSocket
|
||||
module.exports = AIChatSocket
|
||||
|
||||
Reference in New Issue
Block a user