liveh5-nuxt/app/utils/websocket.ts
xingyy 779dc84356 refactor(websocket): 重构 WebSocket 连接和管理
- 在 checkoutPage 中添加全局 WebSocket 客户端实例
- 移除 payment 中的 openRefreshResults 函数
- 更新 authStore,移除不再使用的 openRefreshResults
- 优化 WebSocketClient 类,移除冗余的 token 参数
- 在 nuxt.config.js 中添加 SSL 证书加载逻辑
2025-03-02 10:58:24 +08:00

62 lines
1.8 KiB
TypeScript

export class WebSocketClient {
private socket: WebSocket | null = null
private baseUrl: string
constructor(baseUrl: string, token: string) {
this.baseUrl = baseUrl
}
connect(path: string, params: Record<string, any> = {}) {
// 如果存在旧连接,先关闭
this.disconnect()
// 构建参数对象,自动添加 token
const queryParams = {
...params
}
// 构建查询字符串
const queryString = '?' + Object.entries(queryParams)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&')
// 构建完整的 WebSocket URL
const wsUrl = `${this.baseUrl}${path}${queryString}`
this.socket = new WebSocket(wsUrl)
return {
onOpen: (callback: () => void) => {
this.socket!.onopen = callback
},
onMessage: (callback: (data: any) => void) => {
this.socket!.onmessage = (event) => {
console.log('websocket收到消息', event)
try {
const data = JSON.parse(event.data)
callback(data)
} catch (error) {
console.error('解析消息失败:', error)
}
}
},
onClose: (callback: () => void) => {
this.socket!.onclose = callback
},
onError: (callback: (error: Event) => void) => {
this.socket!.onerror = callback
}
}
}
disconnect() {
if (this.socket) {
this.socket.close()
this.socket = null
}
}
isConnected() {
return this.socket?.readyState === WebSocket.OPEN
}
}