Files
shoot-miniprograms/src/websocket.js

77 lines
1.5 KiB
JavaScript
Raw Normal View History

2025-05-28 23:49:17 +08:00
let socket = null;
2025-05-29 23:45:44 +08:00
let heartbeatInterval = null;
2025-05-28 23:49:17 +08:00
/**
2025-05-29 23:45:44 +08:00
* 建立 WebSocket 连接
2025-05-28 23:49:17 +08:00
*/
2025-05-29 23:45:44 +08:00
function createWebSocket(token, onMessage) {
2025-05-28 23:49:17 +08:00
socket = uni.connectSocket({
url: `ws://120.79.241.5:8000/socket?authorization=${token}`,
2025-05-29 23:45:44 +08:00
success: () => console.log("websocket 连接成功"),
2025-05-28 23:49:17 +08:00
});
// 接收消息
uni.onSocketMessage((res) => {
2025-05-29 23:45:44 +08:00
if (onMessage) onMessage(res.data);
2025-05-28 23:49:17 +08:00
});
// 错误处理
uni.onSocketError((err) => {
console.error("WebSocket 错误", err);
});
2025-06-05 17:43:22 +08:00
uni.onSocketClose((result) => {
console.log("WebSocket 已关闭", result);
2025-06-08 13:55:09 +08:00
socket = uni.connectSocket({
url: `ws://120.79.241.5:8000/socket?authorization=${token}`,
success: () => console.log("websocket 连接成功"),
});
2025-05-28 23:49:17 +08:00
});
2025-05-29 23:45:44 +08:00
// 启动心跳
startHeartbeat();
}
function closeWebSocket() {
2025-05-30 13:58:43 +08:00
if (socket) {
socket.close();
stopHeartbeat();
}
2025-05-28 23:49:17 +08:00
}
/**
2025-05-29 23:45:44 +08:00
* 启动心跳
2025-05-28 23:49:17 +08:00
*/
2025-05-29 23:45:44 +08:00
function startHeartbeat() {
stopHeartbeat(); // 防止重复启动
heartbeatInterval = setInterval(() => {
if (socket && uni.sendSocketMessage) {
uni.sendSocketMessage({
2025-06-05 17:43:22 +08:00
data: {
event: "ping",
data: {},
},
2025-05-29 23:45:44 +08:00
fail: (err) => {
console.error("发送心跳失败", err);
},
});
}
}, 5000);
2025-05-28 23:49:17 +08:00
}
/**
2025-05-29 23:45:44 +08:00
* 停止心跳
2025-05-28 23:49:17 +08:00
*/
2025-05-29 23:45:44 +08:00
function stopHeartbeat() {
if (heartbeatInterval) {
clearInterval(heartbeatInterval);
heartbeatInterval = null;
2025-05-28 23:49:17 +08:00
}
}
export default {
2025-05-29 23:45:44 +08:00
createWebSocket,
2025-05-28 23:49:17 +08:00
closeWebSocket,
};