WebSocket 封裝,vue3專案 拿來即用

好色的菜狗發表於2024-10-14
vue3專案,借鑑了網上的一些,感覺不太適合,就自己邊借鑑,邊弄了一個,複製即用
// useWebSocket.ts
import { ref, onMounted, onUnmounted } from 'vue';

export interface SamListData {
    // ...你的 SamListData 介面定義
}

export interface WebSocketResponse {
    data: SamListData[];
}

export function useWebSocket(url: string, reconnectInterval: number = 5000) {
    const data = ref<any>({});
    const connected = ref(false);
    let socket: WebSocket | null = null;

    function connect() {
        socket = new WebSocket(url);

        socket.onopen = () => {
            connected.value = true;
            // 連線成功後傳送資料請求
            // console.log('連線成功後')
            // socket?.send(JSON.stringify({ request: 'getData' }));
        };

        socket.onmessage = (event) => {
            // console.log('WebSocket 11111:', JSON.parse(event.data));
            // const response: WebSocketResponse = JSON.parse(event.data);
            if (event.data && JSON.parse(event.data).length > 0) {
                data.value = {
                    id: Math.floor(Math.random() * (9999999 - 1000000 + 1)) + 1000000,
                    data: JSON.parse(event.data),
                };
            }
        };

        socket.onerror = (event) => {
            console.log('WebSocket error:', event);
        };

        socket.onclose = (event) => {
            connected.value = false;
            // console.log('WebSocket closed:', event);
            // 嘗試重新連線
            setTimeout(connect, reconnectInterval);
        };
    }
    // 可以在需要的時候傳送訊息 sendMessage({ request: 'getData' })
    function sendMessage(message: any) {
        if (connected.value && socket) {
            socket.send(JSON.stringify(message));
        }
    }

    onMounted(() => {
        connect();
    });

    onUnmounted(() => {
        if (socket) {
            socket.close();
        }
    });
    return {
        data,
        connected,
        sendMessage,
    };
}

  


// 使用const { data, connected, sendMessage } = useWebSocket('ws://192.168.1.1:9500/api/websocket/0120001')
// watch(data, (newData) => {
// console.log('Data updated:', newData)
// console.log('connected', connected)
// })
// 可以在需要的時候傳送訊息
// sendMessage({ request: 'getData' })
// connected 這個是連線狀態

相關文章