代码更新

This commit is contained in:
GaoHao
2025-03-12 14:13:29 +08:00
parent 2f1523d4e9
commit c2135c6119
105 changed files with 2026 additions and 278 deletions

View File

@@ -18,8 +18,11 @@ class WebsocketUtil {
this.initializeWebSocket();
}
// 初始化 WebSocket 连接
initializeWebSocket() {
// 初始化 WebSocket 连接
initializeWebSocket() {
if( this.isOpen){
return
}
this.socketTask = uni.connectSocket({
url: this.url,
success: () => {
@@ -35,13 +38,16 @@ class WebsocketUtil {
this.socketTask.onOpen((res) => {
console.log('WebSocket连接正常==',res);
this.send(JSON.stringify({"type": "ping_interval22"}));
this.isOpen = true;
// 连接成功后启动心跳和消息监听
this.startHeartbeat();
this.listenForMessages();
});
this.socketTask.onError((res) => {
console.log('WebSocket连接失败==',res);
this.reconnect();
});
// 注意:这里的 onClose 监听器应该放在 uni.connectSocket 调用之后
this.socketTask.onClose((result) => {
this.isOpen = false;
@@ -83,10 +89,11 @@ class WebsocketUtil {
// 监听 WebSocket 消息
listenForMessages() {
if (this.socketTask) {
this.socketTask.onMessage((res) => {
this.socketTask.onMessage((res) =>{
const { data } = res;
this.messageCallbacks.forEach(callback => callback(data.toString())); // 假设 data 是字符串或可转换为字符串
});
this.send("WebSocket连接正常");
} else {
console.error('WebSocket 连接尚未建立,无法监听消息');
}
@@ -125,7 +132,7 @@ class WebsocketUtil {
// 外部注销消息回调函数
offMessage(callback) {
this.messageCallbacks = this.messageCallbacks.filter(cb => cb !== callback);
this.messageCallbacks = []
}
// 销毁 WebSocket 连接,清理资源