- 移除多处 console.log 语句,清理无用代码 - 在消息组件中添加 info 类型配置并实现 info 消息显示功能 - 优化 WebSocket 消息处理逻辑,提高代码可读性
65 lines
1.8 KiB
TypeScript
65 lines
1.8 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) => {
|
|
|
|
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
|
|
}
|
|
} |