封装工具类:
// uniapp 版本的 webSocket 工具类
export interface UniWebSocketChatParams {
url: string,
onmessage: (event: UniApp.OnSocketMessageCallbackResult) => void,// 消息处理函数
onopen: () => void,// 成功建立链接函数
onerror: (event: UniApp.GeneralCallbackResult) => void,// 异常处理函数
onclose: () => void,// 关闭处理函数
}
export class UniWebSocketService {
private socketTask: UniApp.SocketTask | null = null
// 建立链接
connect(params: UniWebSocketChatParams) {
this.disconnect() // 确保旧连接断开
this.socketTask = uni.connectSocket({
url: params.url,
complete: () => {
}
})
if (this.socketTask) {
this.socketTask.onOpen(() => {
console.log('WebSocket 连接已开启')
if (params.onopen) {
params.onopen()
}
})
this.socketTask.onMessage((result) => {
if (params.onmessage) {
params.onmessage(result)
} else {
console.log('收到消息:', result.data)
}
})
this.socketTask.onError((error) => {
console.error('WebSocket 错误:', error)
if (params.onerror) {
params.onerror(error)
}
})
this.socketTask.onClose(() => {
console.log('WebSocket 连接已关闭')
if (params.onclose) {
params.onclose()
}
})
}
}
disconnect(code?: number, reason?: string) {
if (this.socketTask) {
this.socketTask.close({
code: code || 1000, // Normal closure
reason: reason || 'Client initiated close'
})
console.log('关闭 WebSocket 连接')
}
}
// 发送消息
sendMessage(message: string) {
if (this.socketTask) {
this.socketTask.send({
data: message,
success: () => console.log('消息发送成功'),
fail: () => console.log('消息发送失败')
})
} else {
console.log('WebSocket 连接未开启或已关闭,无法发送消息')
}
}
isConnected(): boolean {
// 注意:UniApp 不直接提供检查连接状态的方法,此函数需要根据实际情况调整
return !!this.socketTask
}
}
export const uniWebSocketService = new UniWebSocketService()
使用示例:
// 定义 WebSocket 连接的参数
const params: UniWebSocketChatParams = {
url: 'wss://example.com/ws',
onopen: () => {
console.log('WebSocket 连接成功');
// 连接成功后发送一条消息
uniWebSocketService.sendMessage('Hello, server!');
},
onmessage: (event) => {
console.log('收到消息:', event.data);
// 处理接收到的消息
},
onerror: (error) => {
console.error('WebSocket 发生错误:', error);
},
onclose: () => {
console.log('WebSocket 连接已关闭');
}
};
// 连接 WebSocket
uniWebSocketService.connect(params);
// 发送一条消息
function sendMessageToServer() {
if (uniWebSocketService.isConnected()) {
uniWebSocketService.sendMessage('This is a test message.');
} else {
console.log('WebSocket 未连接,无法发送消息');
}
}
// 断开 WebSocket 连接
function disconnectWebSocket() {
uniWebSocketService.disconnect(1000, '客户端关闭连接');
}