xuchang-new/websocket/server.js

96 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2024-04-19 16:38:41 +08:00
const { WebSocket } = require("ws");
const { getRandomAlarmList } = require("./fakedata/alarmList");
const wss = new WebSocket.Server({ port: 9800 });
console.log('[websocket] server created');
2024-04-19 16:11:10 +08:00
wss.on("connection", function (ws, req) {
console.log(
2024-04-19 16:38:41 +08:00
"[用户连接]: ",
2024-04-19 16:11:10 +08:00
req.socket.remoteAddress,
2024-04-19 16:38:41 +08:00
"当前总用户数:",
2024-04-19 16:11:10 +08:00
wss.clients.size
);
ws.on("open", function () {
2024-04-19 16:38:41 +08:00
console.log('[websocket] opened');
2024-04-19 16:11:10 +08:00
ws.send("connected");
});
ws.on("message", function (msg) {
2024-04-19 16:38:41 +08:00
console.log("[==>]", msg);
2024-04-19 16:11:10 +08:00
});
ws.on("error", console.error);
const timer = setInterval(() => {
2024-04-19 16:38:41 +08:00
sendMsg(ws, "alarmList"); // 报警信息
}, 10 * 1000);
2024-04-19 16:11:10 +08:00
ws.on("close", function () {
console.log("停止监听");
clearInterval(timer);
});
});
function sendMsg(ws, type) {
let data = {};
switch (type) {
2024-04-19 16:38:41 +08:00
case "alarmList":
const alarmList = getRandomAlarmList(Math.floor(Math.random() * 10) + 1);
alarmList.forEach((str) => {
const [code, detail] = str.split(",");
data[code] = detail;
});
break;
2024-04-19 16:11:10 +08:00
case "kiln-info":
for (const key in template.kilnInfo) {
data[key] = utils.getRandom(template.kilnInfo[key]);
}
break;
case "energy-cost":
for (const key in template.energyCost) {
data[key] = utils.getRandom(template.energyCost[key]);
}
break;
case "run-state":
data = template.runState;
data.fireDirection =
Math.floor(Math.random() * 10) % 2 === 0 ? "南火" : "北火";
break;
case "realtime":
/** 天然气 实时流量 */
data.gasii = template.realtime.gasii.map((v) => utils.getRandom(v));
/** 助燃风 实时流量 */
data.wind = template.realtime.wind.map((v) => utils.getRandom(v));
break;
case "his-trend":
const hisTrend = {
gas: {},
wind: {},
};
Object.keys(template.hisTrend.gas).forEach((key) => {
hisTrend.gas[key] = template.hisTrend.gas[key].map((v) =>
utils.getRandom(v)
);
});
Object.keys(template.hisTrend.wind).forEach((key) => {
hisTrend.wind[key] = template.hisTrend.wind[key].map((v) =>
utils.getRandom(v)
);
});
data = hisTrend;
break;
case "gas":
// data = template.gas;
break;
case "kiln-top":
// data = template.kilnTop;
break;
case "kiln-bottom":
// data = template.kilnBottom;
break;
default:
// data = 'You are connected!';
break;
}
ws.send(JSON.stringify({ type, data }));
}