最近用websocket和后端通信发送数据和接收到数据的处理打算记录下,需求是前端先通过websocket向后端发送要接收数据的设备ID后端收到后返回ID对应的数据
let lockReconnect=false;
let ip=location.host+'alarmNotify';
let wsUrl="wss://"+ip;
let ws;
let tt;
let latAadLngData;
let devArr = [];
creatMenus()
function creatMenus(definDataId) {
controller.getDevInfo((res) => {
latAadLngData = res;
for (let i = 0; i < latAadLngData.length; i++) {
devArr.push(latAadLngData[i].devId);
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)
};
ws.onmessage=function(event){
let serverData = JSON.parse(event.data)
}
}
function handleMessage(serverData){
let definDatas = Object.keys(serverData.content);
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) {
$(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)
}
|