如何搭建websocket及使用

保持一个长连接,当服务端有新的消息,能够实时的推送到使用方。像知乎的点赞通知、评论等,都可以使用WebSocket通信。

那该如何搭建呢

首先在utils文件夹下创建一个websocket.ts文件

import { onUnmounted } from 'vue';
const actions = {
    cmdList: [{ cmd: "C002" }, { cmd: 'C001' }],  //需要发往后端的命令 后端根据命令返回相应的数据
};
let randnum = localStorage.getItem('randnum'); //获取随机数
export function projectNoise() {
    var websocket: any = null
    // 判断当前环境是否支持Websocket
    if (window.WebSocket) {
        if (!websocket) {
            websocket = new WebSocket(`ws:172.16.10.52:9072/websocket/server/${randnum}`);
        } else {
            console.log('不支持websocket')
        }
        // 连接到消息得回调方法
        websocket.onmessage = function (e: any) {
            let res = JSON.parse(e.data);
            if (res.indexCmd == 'C001') {
                console.log(res)   //根据命令不同打印不一样的数据
            } else if (res.indexCmd == 'C002') {
                console.log(res)
            }
        }
        // 接受到服务端关闭连接时的回调方法
        websocket.onclose = function () {
            console.log('onclose断开连接')
            clearInterval(time);
        }
    }
.    //每10秒向后端发送一次ping
    let time = setInterval(() => {
        websocket.send('ping');
    }, 10000);
    // 连接成功建立得回调方法
    websocket.onopen = function (e: any) {
        websocket.send(JSON.stringify(actions));
    }
    //离开当前页面断开websocket 及销毁定时器
    onUnmounted(() => {
        websocket.close()
        clearInterval(time);
    })
}

建立完成后即可在需要使用的组件里面进行数据使用

你可能感兴趣的:(前端,javascript)