xuchang-screen/websocket/server.ts

94 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-09-10 15:09:12 +08:00
import { WebSocket, WebSocketServer } from 'ws';
import demoData from './demo.json';
2023-09-10 20:35:29 +08:00
import utils from './utils';
2023-09-10 15:09:12 +08:00
const wss = new WebSocketServer({ port: 9800 });
2023-09-10 21:44:05 +08:00
const frequency = 10; // seconds
2023-09-10 15:09:12 +08:00
wss.on('connection', function (ws, req) {
// console.log("ws", ws);
console.log(
'Client in: ',
req.socket.remoteAddress,
'current users:',
wss.clients.size,
);
// ws.on("error", console.error);
// ws.emit("message", "connected");
ws.on('open', function () {
console.log('connected');
ws.send('connected');
});
ws.on('message', function (msg) {
console.log('message from client', msg);
ws.send('echo ' + msg.toString());
});
ws.on('error', console.error);
const timer = setInterval(() => {
2023-09-10 20:35:29 +08:00
sendMsg(ws, 'kiln-info'); // 窑炉信息
2023-09-10 21:44:05 +08:00
sendMsg(ws, 'run-state'); // 运行状态
sendMsg(ws, 'energy-cost'); // 运行状态
// sendMsg(ws, 'fan');
// sendMsg(ws, 'gas');
// sendMsg(ws, 'kiln-top');
// sendMsg(ws, 'kiln-bottom');
2023-09-10 15:09:12 +08:00
}, frequency * 1000);
ws.on('close', function () {
console.log('停止监听');
clearInterval(timer);
});
});
2023-09-10 21:44:05 +08:00
type MsgType =
| 'kiln-info'
| 'run-state'
| 'energy-cost'
| 'fan'
| 'gas'
| 'kiln-top'
| 'kiln-bottom';
2023-09-10 15:09:12 +08:00
function sendMsg(ws: WebSocket, type: MsgType) {
2023-09-10 20:35:29 +08:00
let data: {
[key: string]: string;
} = {};
2023-09-10 15:09:12 +08:00
switch (type) {
2023-09-10 20:35:29 +08:00
case 'kiln-info':
for (const key in demoData.kilnInfo) {
data[key] = utils.getRandom(
demoData.kilnInfo[key as keyof typeof demoData.kilnInfo],
);
}
2023-09-10 15:09:12 +08:00
break;
2023-09-10 21:44:05 +08:00
case 'energy-cost':
for (const key in demoData.energyCost) {
data[key] = utils.getRandom(
demoData.energyCost[key as keyof typeof demoData.energyCost],
);
}
break;
case 'run-state':
data = demoData.runState;
break;
2023-09-10 15:09:12 +08:00
case 'fan':
2023-09-10 20:35:29 +08:00
// data = demoData.fan;
2023-09-10 15:09:12 +08:00
break;
case 'gas':
2023-09-10 20:35:29 +08:00
// data = demoData.gas;
2023-09-10 15:09:12 +08:00
break;
case 'kiln-top':
2023-09-10 20:35:29 +08:00
// data = demoData.kilnTop;
2023-09-10 15:09:12 +08:00
break;
case 'kiln-bottom':
2023-09-10 20:35:29 +08:00
// data = demoData.kilnBottom;
2023-09-10 15:09:12 +08:00
break;
default:
2023-09-10 20:35:29 +08:00
// data = 'You are connected!';
2023-09-10 15:09:12 +08:00
break;
}
// console.log("sendMsg: ", ws);
// ws.emit("message", JSON.stringify(data));
2023-09-10 20:35:29 +08:00
ws.send(JSON.stringify({ type, data }));
2023-09-10 15:09:12 +08:00
}