bmh_admin/controller/socket.js
2025-03-14 17:04:22 +08:00

123 lines
5.4 KiB
JavaScript

const WebSocket = require('ws');
const util = require("../util/common");
var { entityHJ, simuStatus } = require("../util/variable");
const deltaT = 1000;
const createServer = () => {
// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 9000 });
wss.on('connection', function connection(ws) {
console.log('新客户端已连接');
// 定时发送消息
const intervalId = setInterval(() => {
var simType = simuStatus["运行状态"];
if (simType == 1) {
var currRadio = simuStatus["仿真倍速"];
var currTime = simuStatus["当前时间"];
if (entityHJ.size > 0) {
var array = [];
for (const [key, value] of entityHJ) {
const keysArray = [...value.keys()];
var indexKey = util.lower_bound(keysArray, currTime);
if (indexKey < keysArray.length) {
let point = {};
var second = keysArray[indexKey];
if (indexKey == 0) {
point = value.get(second);
}
else {
var first = keysArray[indexKey - 1];
var delta_time = second - first;
if (delta_time == 0.0) {
point = value.get(first);
}
else {
var pointfirst = value.get(first);
var pointsecond = value.get(second);
point["空速"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["空速"],
pointsecond["空速"]);
point["升降率"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["升降率"],
pointsecond["升降率"]);
point["过载"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["过载"],
pointsecond["过载"]);
point["马赫数"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["马赫数"],
pointsecond["马赫数"]);
point["经度"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["经度"],
pointsecond["经度"]);
point["纬度"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["纬度"],
pointsecond["纬度"]);
point["海拔"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["海拔"],
pointsecond["海拔"]);
point["航向角"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["航向角"],
pointsecond["航向角"]);
point["俯仰角"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["俯仰角"],
pointsecond["俯仰角"]);
point["倾斜角"] = util.interpolate(
(currTime - first) / delta_time,
pointfirst["倾斜角"],
pointsecond["倾斜角"]);
}
}
point["BDID"] = key;
array.push(point);
}
}
const message = {
time: currTime,
data: array
};
ws.send(JSON.stringify(message)); // 发送JSON格式的消息
}
var accTime = deltaT * currRadio;
currTime += accTime;
simuStatus["当前时间"] = currTime;
}
}, deltaT); // 每5秒发送一次消息
// 可以在这里添加更多的逻辑,例如当客户端关闭连接时清除定时器等
ws.on('close', () => {
clearInterval(intervalId); // 清除定时器,防止内存泄漏
console.log('客户端已断开连接');
});
});
console.log('WebSocket服务器正在运行在ws://localhost:9000');
}
module.exports = createServer()