websocket数据处理

最近用websocket和后端通信发送数据和接收到数据的处理打算记录下,需求是前端先通过websocket向后端发送要接收数据的设备ID后端收到后返回ID对应的数据

let lockReconnect=false;//避免重复连接
let ip=location.host+'alarmNotify';
let wsUrl="wss://"+ip;
let ws;
let tt;
let latAadLngData;
let devArr = [];//存放传入后端ID的数组
 creatMenus()

    function creatMenus(definDataId) {
        controller.getDevInfo((res) => {
            latAadLngData = res;
            for (let i = 0; i < latAadLngData.length; i++) {
                devArr.push(latAadLngData[i].devId);//获取数组ID
                lis += "<li data-devId=" + latAadLngData[i].devId + " class='detail' id='details" + i +
                    "'><button value=\"" + latAadLngData[i].lat + ',' +
                    latAadLngData[i].lng + ',' + latAadLngData[i].deptName + ',' + latAadLngData[i]
                    .streamAddr + ',' +
                    "\" style='margin:6px 0px;height:36px; width: 300px;display: block;' οnclick='position(this)'>" +
                    latAadLngData[i].devName + "</button></li>"
            }
            $('#latlngContainer').html(lis)
        })
    }
function createWebSocket(wsUrl){
    try{
        ws=new WebSocket(wsUrl);
        init()
     }catch(e){
        reconnect(wsUrl);
     }
}
function init(){
ws.onclose=function(){
console.log('连接关闭')
};
ws.onerror=function(){
console.log('发生异常')
};
ws.onopen=function(){
consloe.log('连接成功')
 let data = JSON.stringify({
                "content": {},
                "devIDs": devArr,
                "msgTime": 1644912412517,
                "msgType": 4,
                "msgUUID": "0d646108-d0a6-4a3b-b595-52324bf0f98c"
            })
            ws.send(data)//向后端发送设备ID数据
};
ws.onmessage=function(event){
 let serverData = JSON.parse(event.data)//接收到后端返回数据处理
}
}
function handleMessage(serverData){
 let definDatas = Object.keys(serverData.content);//拿到后端返回的ID值可能是数组
   let serveType = serverData.msgType;
    if (serveType == '4') {
            const lis = document.getElementsByClassName('detail')//获取列表元素
            for (let i = 0; i < lis.length; i++) {   //循环遍历获取到的元素
                if (definDatas.indexOf($(lis[i]).attr('data-devId')) > -1) {   //判断拿到的数据是否和元素的ID相匹配
                    $(lis[i]).addClass('alarmClass')   //如果匹配就添加一个元素类名
                    let elm = document.getElementsByName('alarmClass');
                } else {
                    $(lis[i]).removeClass('alarmClass')
                }
            }
        }
}
function reconnect(url){
if(lockReconnect){
return;
}
lockReconnect = true;
        tt && clearTimeout(tt);
        tt = setTimeout(function () {
            createWebSocket(url);
            lockReconnect = false;
        }, 5000)
}

版权声明:本文为lxtalent原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。