WebSocket 封装,vue3项目 拿来即用

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 这个是连接状态
posted @ 2024-10-14 16:08  好运的菜狗  阅读(134)  评论(0编辑  收藏  举报