vue-socket.io以及原生websocket的使用

2023-12-13 06:33:40

vue3使用socket.io

1、安装 
npm install vue-socket.io

2、创建socket.js文件

export const registerSockets = (sockets, proxy) => {
    sockets &&
        Object.keys(sockets).forEach((t) => {
            // console.log(t);
            // "subscribe" !== t &&
            //     "unsubscribe" !== t &&
                proxy.$socket.emitter.addListener(t, sockets[t], proxy);
        });
};

export const destroySockets = (sockets, proxy) => {
    sockets &&
        Object.keys(sockets).forEach((t) => {
            proxy.$socket.emitter.removeListener(t, proxy);
        });
};

3、 main.js使用

import VueSocketIO from 'vue-socket.io';
import { registerSockets, destroySockets } from './service/utils/sockets';
const scUrl =
    import.meta.env.VITE_SOCKET_URL;
const sockets = new VueSocketIO({
    debug: true,
    connection: scUrl,
});

app.config.globalProperties.$socket = sockets;
// 监听事件
app.config.globalProperties.$addSockets = registerSockets;
// 移除事件
app.config.globalProperties.$removeSockets = destroySockets;

4、组件使用


    const sockets = {
    //监听事件名
        deviceRealData(data) {
           console.log(data)
        },
        deviceRealAlarm(data) {
             console.log(data)
        }
    }
	onMounted(async () => {
        proxy.$addSockets(sockets, proxy);
    })
    onBeforeUnmount(() => {
        proxy.$removeSockets(sockets, proxy);
    });
    
       // 开启数据推送 发送事件
    function opendata() {
        proxy.$socket.io.emit('openRealData', state.currentData.deviceSn)
        proxy.$socket.io.emit('openRealAlarm', state.currentData.deviceSn)
    }
    // 关闭数据推送
    function stopData() {
        proxy.$socket.io.emit('closeRealData')
        proxy.$socket.io.emit('closeRealAlarm')
    }

原生websocket

    let socket;
    / Websoket连接成功事件
    const websocketonopen = (res) => {
        console.log("WebSocket连接成功", res);
    };
    // Websoket接收消息事件
    const websocketonmessage = (res) => {
    console.log("接收消息", res);
     };
    // Websoket连接错误事件
    const websocketonerror = (res) => {
        console.log("连接错误", res);
    };
    // Websoket断开事件
    const websocketclose = (res) => {
        console.log("断开连接", res);
    };
     onMounted(() => {
        const wsurl =
            import.meta.env.VITE_SOCKET_URL;
        socket = new WebSocket(wsurl);
        socket.onopen = websocketonopen;
        socket.onmessage = websocketonmessage;
        socket.onerror = websocketonerror;
        socket.onclose = websocketclose;
    })
    onBeforeUnmount(() => {
        // 关闭连接
        socket.close();
        // 销毁 websocket 实例对象
        socket = null;
    });
      //筛选器:提交
    function handleFilterSubmit() {
    //发送事件
        socket.send(JSON.stringify({ deviceSN:queryParams.value.input}))
    }
    

文章来源:https://blog.csdn.net/weixin_46352558/article/details/134837170
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。