- 新增 utils/config.js:DEBUG 一处控制 health/user/ws 三个服务的本地与线上地址, 顺带集中 appId、识别链路超时、WS 心跳与重连参数 - request.js / api.js / chatmsg.js 改为从 config 取值,删除各自硬编码的基址 - 修正本地调试时聊天 WS 仍连线上导致 token 查不到用户的问题 - PROJECT_GUIDE 同步接口与配置约定
201 lines
5.3 KiB
JavaScript
201 lines
5.3 KiB
JavaScript
// WS 基址与 HTTP 同源(config.DEBUG):本地调试时 HTTP 走本机,聊天也必须连本机,
|
|
// 否则本机签发的 token 到线上服务端查不到用户,只会回「请先登录」
|
|
const config = require('./config.js')
|
|
const WS_BASE_URL = config.WS_BASE_URL
|
|
|
|
class AIChatSocket {
|
|
constructor(url = `${WS_BASE_URL}/chat`, options = {}) {
|
|
this.url = url
|
|
this.options = {
|
|
heartbeatInterval: config.WS_HEARTBEAT_INTERVAL,
|
|
autoReconnect: true,
|
|
maxReconnectAttempts: config.WS_MAX_RECONNECT_ATTEMPTS,
|
|
reconnectDelay: config.WS_RECONNECT_DELAY,
|
|
...options
|
|
}
|
|
|
|
this.socketTask = null
|
|
this.isConnected = false
|
|
this.isConnecting = false
|
|
this.connectPromise = null
|
|
this.reconnectAttempts = 0
|
|
|
|
this._openCallback = null
|
|
this._closeCallback = null
|
|
this._errorCallback = null
|
|
this._messageCallback = null
|
|
this._heartbeatTimer = null
|
|
}
|
|
|
|
// 连接 Promise 单飞:调用方必须 await 成功后再发送,避免断线后的首条消息竞态。
|
|
connect() {
|
|
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 连接失败'))
|
|
}
|
|
|
|
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) {
|
|
fail(new Error('SocketTask creation failed'))
|
|
return
|
|
}
|
|
|
|
this.socketTask.onOpen(() => {
|
|
this.isConnected = true
|
|
this.reconnectAttempts = 0
|
|
this._startHeartbeat()
|
|
if (this._openCallback) this._openCallback()
|
|
succeed()
|
|
})
|
|
|
|
this.socketTask.onClose((res) => {
|
|
this.isConnected = false
|
|
this._stopHeartbeat()
|
|
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) => {
|
|
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
|
|
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) {
|
|
return Promise.reject(new Error('WebSocket 尚未连接'))
|
|
}
|
|
|
|
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
|
|
const task = this.socketTask
|
|
this.socketTask = null
|
|
this.isConnected = false
|
|
this.isConnecting = false
|
|
if (task) {
|
|
task.close({
|
|
code: 1000,
|
|
reason: 'User closed',
|
|
fail: (err) => console.error('[AIChatSocket] Close failed:', err)
|
|
})
|
|
}
|
|
}
|
|
|
|
onOpen(callback) {
|
|
this._openCallback = callback
|
|
}
|
|
|
|
onClose(callback) {
|
|
this._closeCallback = callback
|
|
}
|
|
|
|
onError(callback) {
|
|
this._errorCallback = callback
|
|
}
|
|
|
|
onMessage(callback) {
|
|
this._messageCallback = callback
|
|
}
|
|
|
|
_reconnect() {
|
|
this.reconnectAttempts++
|
|
setTimeout(() => {
|
|
if (!this.options.autoReconnect || this.isConnected) return
|
|
this.connect().catch((err) => {
|
|
console.error('[AIChatSocket] Reconnect failed:', err)
|
|
})
|
|
}, this.options.reconnectDelay)
|
|
}
|
|
|
|
_startHeartbeat() {
|
|
this._stopHeartbeat()
|
|
this._heartbeatTimer = setInterval(() => {
|
|
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)
|
|
}
|
|
|
|
_stopHeartbeat() {
|
|
if (this._heartbeatTimer) {
|
|
clearInterval(this._heartbeatTimer)
|
|
this._heartbeatTimer = null
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = AIChatSocket
|