聊天室完成

This commit is contained in:
2025-12-24 16:32:06 +08:00
parent 898da3a2c6
commit ad03f3f2db
16 changed files with 432 additions and 53 deletions

View File

@@ -3,6 +3,12 @@
* 支持STOMP协议和uni.connectSocket API
*/
// uni-app 类型声明
declare const uni: {
connectSocket: (options: any) => any
getStorageSync: (key: string) => any
}
interface StompFrame {
command: string
headers: Record<string, string>
@@ -31,12 +37,49 @@ export class WebSocketClient {
/**
* 连接WebSocket
*/
connect(url: string, token: string): Promise<void> {
async connect(url: string, token: string): Promise<void> {
// 如果已经连接到相同的URL直接返回
if (this.connected && this.url === url) {
console.log('[WebSocket] 已连接到相同URL跳过')
return Promise.resolve()
}
// 如果有旧连接,先关闭并等待关闭完成
if (this.socketTask) {
console.log('[WebSocket] 关闭旧连接')
await new Promise<void>((resolveClose) => {
try {
this.socketTask.close({
success: () => {
console.log('[WebSocket] 旧连接已关闭')
this.socketTask = null
this.connected = false
resolveClose()
},
fail: () => {
console.warn('[WebSocket] 关闭旧连接失败')
this.socketTask = null
this.connected = false
resolveClose()
}
})
} catch (e) {
console.warn('[WebSocket] 关闭旧连接异常:', e)
this.socketTask = null
this.connected = false
resolveClose()
}
})
// 等待一小段时间确保旧连接完全关闭
await new Promise(resolve => setTimeout(resolve, 100))
}
this.url = url
this.token = token
console.log('[WebSocket] 开始连接:', url)
return new Promise((resolve, reject) => {
this.url = url
this.token = token
console.log('[WebSocket] 开始连接:', url)
this.socketTask = uni.connectSocket({
url: url,
@@ -184,7 +227,7 @@ export class WebSocketClient {
success: () => {
console.log('[WebSocket] 发送成功:', frame.command)
},
fail: (err) => {
fail: (err: any) => {
console.error('[WebSocket] 发送失败:', err)
}
})