update websocket

This commit is contained in:
lb 2023-12-06 16:37:53 +08:00
parent 5f92580c7e
commit 42e5bea184

View File

@ -9,23 +9,36 @@ export function randomInt(min, max, includeMax = false) {
return num; return num;
} }
export class WsClient { /**
static wsServer = "ws://192.168.1.12:8081/xc-screen/websocket/xc001"; * new XClient('ws://192.168.1.12:8081/xc-screen/websocket/xc001', 'DCS')
static socket = null; */
static tryCount = 0; class XClient {
constructor(url, name, onmessage) {
constructor() { this.url = url;
if (WsClient.socket) return; this.name = name;
WsClient.socket = new WebSocket(WsClient.wsServer); this.ws = new WebSocket(url);
WsClient.socket.onopen = () => { this.ws.onopen = () => {
console.log("[*] websocket connected!"); console.log(`[*] ${this.name} ws connected`);
}; };
WsClient.socket.onmessage = (e) => { this.ws.onmessage = onmessage;
this.ws.onerror = (err) => {
console.log("[*] websocket error!", err, err.data);
};
this.ws.onclose = (e) => {
console.log(`[*] ${this.name} ws closed`);
};
}
}
new XClient(
"ws://192.168.1.12:8081/xc-screen/websocket/xc001",
"DCS_DATA",
(msg) => {
let serializedData = null; let serializedData = null;
try { try {
serializedData = JSON.parse(e.data); serializedData = JSON.parse(msg.data);
} catch (error) { } catch (error) {
console.log("[*] websocket: [unable to serialize] ---> ", e); console.log("[*] websocket: [unable to serialize] ---> ", msg);
} }
switch (serializedData?.type) { switch (serializedData?.type) {
case "KilnInfo": { case "KilnInfo": {
@ -129,20 +142,34 @@ export class WsClient {
break; break;
} }
default: { default: {
console.log("websocket message: [unknown] ---> ", e.data); console.log("websocket message: [unknown] ---> ", msg.data);
} }
} }
}; }
WsClient.socket.onerror = (e) => { );
console.log("[*] websocket error!", e, e.data);
}; new XClient(
WsClient.socket.onclose = (e) => { "ws://192.168.1.74:48080/websocket/message?userId=ENERGY111",
let timer = setTimeout(() => { "MES_DATA",
if (WsClient.tryCount < 3) { (msg) => {
new WsClient(); let serializedData = null;
WsClient.tryCount += 1; try {
} else clearTimeout(timer); serializedData = JSON.parse(msg.data);
}, 30000); } catch (error) {
}; console.log("[*] websocket: [unable to serialize] ---> ", msg);
}
switch (serializedData?.type) {
case "EnergyInfo": {
// 能耗数据
store.dispatch({
type: "energy/setInfo",
payload: serializedData.data,
});
break;
}
default: {
console.log("websocket message: [unknown] ---> ", msg.data);
} }
} }
}
);