wuliu_sy/utils/websocket.js

85 lines
1.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let socket = null;
const HEARTBEAT_INTERVAL = 5000;
let heartbeatTimer = null;
// // 连接到后端 WebSocket并开始心跳
// function connect() {
// WebSocket.connect('ws://your-backend-url');
// startHeartbeat();
// }
// 开始发送心跳消息
function startHeartbeat() {
heartbeatTimer = setInterval(() => {
WebSocket.send('heartbeat');
}, HEARTBEAT_INTERVAL);
}
// 停止发送心跳消息
function stopHeartbeat() {
clearInterval(heartbeatTimer);
}
// 监听收到的消息
WebSocket.onMessage((event) => {
if (event.data === 'heartbeat') {
// 收到心跳响应,重置定时器
resetHeartbeatTimer();
} else {
// 处理其他消息
}
});
// 重置心跳定时器
function resetHeartbeatTimer() {
clearInterval(heartbeatTimer);
startHeartbeat();
}
// 在页面关闭或组件销毁时,关闭 WebSocket 连接并停止心跳
uni.onUnload(() => {
WebSocket.close();
stopHeartbeat();
});
function connect(url) {
socket = uni.connectSocket({
url: url
});
socket.onOpen(() => {
console.log('WebSocket 连接已打开');
});
socket.onError((error) => {
console.error('WebSocket 连接发生错误', error);
});
socket.onClose((e) => {
console.log('WebSocket 连接已关闭', e);
});
socket.onMessage((event) => {
console.log('收到服务器消息', event.data);
// 处理收到的消息
});
}
function send(message) {
socket.send({
data: message
});
}
function close() {
if (socket) {
socket.close();
}
}
export default {
connect,
send,
close
};