完成单组练习接口调试

This commit is contained in:
kron
2025-05-29 23:45:44 +08:00
parent 6466c65b66
commit 9db31ce664
14 changed files with 282 additions and 122 deletions

View File

@@ -1,31 +1,18 @@
// utils/websocket.js
let socket = null;
let messageCallback = null;
let heartbeatInterval = null;
/**
* 连接 WebSocket
* @param {String} url WebSocket 地址
* @param {Function} onMessage 消息回调
* 建立 WebSocket 连接
*/
function connectWebSocket(token, onMessage) {
messageCallback = onMessage;
function createWebSocket(token, onMessage) {
socket = uni.connectSocket({
url: `ws://120.79.241.5:8000/socket?authorization=${token}`,
success: () => {
console.log("连接建立成功");
},
fail: (err) => {
console.error("连接失败", err);
},
success: () => console.log("websocket 连接成功"),
});
// 接收消息
uni.onSocketMessage((res) => {
if (messageCallback) {
messageCallback(res.data);
}
if (onMessage) onMessage(res.data);
});
// 错误处理
@@ -36,39 +23,46 @@ function connectWebSocket(token, onMessage) {
// 关闭处理
uni.onSocketClose(() => {
console.log("WebSocket 已关闭");
socket = null;
});
// 启动心跳
startHeartbeat();
}
/**
* 发送消息
* @param {String} msg 要发送的消息内容
*/
function sendWebSocketMessage(msg) {
if (socket && uni.sendSocketMessage) {
uni.sendSocketMessage({
data: msg,
fail: (err) => {
console.error("发送消息失败", err);
},
});
} else {
console.warn("WebSocket 未连接");
}
}
/**
* 关闭连接
*/
function closeWebSocket() {
if (socket) {
uni.closeSocket();
socket = null;
if (socket) socket.close();
}
/**
* 启动心跳
*/
function startHeartbeat() {
stopHeartbeat(); // 防止重复启动
heartbeatInterval = setInterval(() => {
if (socket && uni.sendSocketMessage) {
console.log("ping");
uni.sendSocketMessage({
data: "ping",
fail: (err) => {
console.error("发送心跳失败", err);
},
});
}
}, 5000);
}
/**
* 停止心跳
*/
function stopHeartbeat() {
if (heartbeatInterval) {
clearInterval(heartbeatInterval);
heartbeatInterval = null;
}
}
export default {
connectWebSocket,
sendWebSocketMessage,
createWebSocket,
closeWebSocket,
};