liveh5-nuxt/app/utils/websocket.ts
xingyy 36793c5c5a feat(live): 实现直播间竞拍功能并优化相关页面
- 新增 artworkBuy API 实现艺术品购买功能
- 重构 WebSocket连接逻辑,优化消息处理- 更新直播间页面,支持实时竞拍和消息提示
-调整艺术详情和用户中心页面样式
- 优化消息组件样式和展示逻辑
2025-02-08 15:21:00 +08:00

65 lines
1.9 KiB
TypeScript

export class WebSocketClient {
private socket: WebSocket | null = null
private baseUrl: string
private token: string
constructor(baseUrl: string, token: string) {
this.baseUrl = baseUrl
this.token = token
}
connect(path: string, params: Record<string, any> = {}) {
// 如果存在旧连接,先关闭
this.disconnect()
// 构建参数对象,自动添加 token
const queryParams = {
token: this.token,
...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('event',event)
try {
const data = JSON.parse(event.data)
console.log('data',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
}
}