Files
shoot-miniprograms/src/websocket.js

69 lines
1.2 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);
});
// 关闭处理
uni.onSocketClose(() => {
console.log("WebSocket 已关闭");
});
2025-05-29 23:45:44 +08:00
// 启动心跳
startHeartbeat();
}
function closeWebSocket() {
if (socket) socket.close();
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) {
console.log("ping");
uni.sendSocketMessage({
data: "ping",
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,
};