cashier-mer/src/utils/ws.js

32 lines
787 B
JavaScript
Raw Normal View History

2024-04-05 13:44:36 +08:00
export const initWS = (token)=>{
let ws = new WebSocket('ws://192.168.1.22:8324?type=mer&token='+token);
ws.onopen = function (e) {
console.log('WebSocket 连接已建立');
// 开始发送心跳
startHeartbeat();
}
ws.onclose = () => {
console.log('WebSocket 连接已关闭');
// 停止发送心跳
stopHeartbeat();
};
let heartbeatTimer = null;
// 开始发送心跳
const startHeartbeat = () => {
heartbeatTimer = setInterval(() => {
console.log('发送心跳消息');
ws.send(JSON.stringify({ type: 'heartbeat' }));
}, 30*1000);
}
// 停止发送心跳
const stopHeartbeat = () => {
clearInterval(heartbeatTimer);
}
return ws;
}