关于vue3+ts使用websocket 并且使用心跳机制

2024-09-12  本文已影响0人  Morbid_D

import { ref } from 'vue';

/**

*/
export function useWebSocket(wsUri: string, heartbeatMessage = 'heartbeat', reconnectInterval = 5000, timeout = 20000) {
// Reactive reference for the WebSocket connection
const websock = ref<WebSocket | null>(null);

// Boolean flag to avoid multiple reconnections simultaneously
const lockReconnect = ref<boolean>(false);

// Variables to hold the timeouts for heartbeat and reconnection logic
let timeoutObj: ReturnType<typeof setTimeout> | null = null;
let serverTimeoutObj: ReturnType<typeof setTimeout> | null = null;
let timeoutnum: ReturnType<typeof setTimeout> | null = null;

/**

// Create a new WebSocket connection
websock.value = new WebSocket(wsUri);

// Set up event handlers for WebSocket
websock.value.onopen = websocketonopen;
websock.value.onerror = websocketonerror;
websock.value.onmessage = websocketonmessage;
websock.value.onclose = websocketclose;

};

/**

/**

/**

// Handle the received data
try {
  const data = JSON.parse(event.data); // Parse the JSON message from the server
  // Process the data as needed (you can customize this part)
  console.log('Parsed data:', data);
} catch (e) {
  console.error('Error parsing JSON:', e); // Log any errors with JSON parsing
}

};

/**

/**

/**

lockReconnect.value = true; // Lock the reconnection to prevent multiple attempts

// Clear any existing reconnection timeouts
timeoutnum && clearTimeout(timeoutnum);

// Attempt reconnection after a delay
timeoutnum = setTimeout(() => {
  initWebSocket(); // Re-initialize WebSocket connection
  lockReconnect.value = false; // Unlock reconnection
}, reconnectInterval); // Reconnect after specified interval

};

/**

/**

/**

// Clear all timeouts related to heartbeat and reconnection
timeoutObj && clearTimeout(timeoutObj);
serverTimeoutObj && clearTimeout(serverTimeoutObj);
timeoutnum && clearTimeout(timeoutnum);

console.log('WebSocket connection closed manually');

};

// Automatically initialize WebSocket on component mount
// onMounted(() => {
// initWebSocket();
// });

// // Automatically close WebSocket on component unmount to prevent memory leaks
// onBeforeUnmount(() => {
// closeWebSocket();
// });

return {
websock, // Expose WebSocket reference
websocketsend, // Expose method to send messages
initWebSocket, // Expose method to manually initialize WebSocket
closeWebSocket // Expose method to manually close WebSocket
};
}
使用
import { useWebSocket } from './useWebSocket'; // Import the WebSocket hook (adjust path as necessary)
const wsUri = ‘wss://’
const { websock, websocketsend, initWebSocket, closeWebSocket } = useWebSocket(wsUri);

上一篇 下一篇

猜你喜欢

热点阅读