import { WebSocket, WebSocketServer } from 'ws'; import demoData from './demo.json'; import utils from './utils'; const wss = new WebSocketServer({ port: 9800 }); const frequency = 10; // seconds 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(() => { sendMsg(ws, 'kiln-info'); // 窑炉信息 sendMsg(ws, 'run-state'); // 运行状态 sendMsg(ws, 'energy-cost'); // 运行状态 // sendMsg(ws, 'fan'); // sendMsg(ws, 'gas'); // sendMsg(ws, 'kiln-top'); // sendMsg(ws, 'kiln-bottom'); }, frequency * 1000); ws.on('close', function () { console.log('停止监听'); clearInterval(timer); }); }); type MsgType = | 'kiln-info' | 'run-state' | 'energy-cost' | 'fan' | 'gas' | 'kiln-top' | 'kiln-bottom'; function sendMsg(ws: WebSocket, type: MsgType) { let data: { [key: string]: string; } = {}; switch (type) { case 'kiln-info': for (const key in demoData.kilnInfo) { data[key] = utils.getRandom( demoData.kilnInfo[key as keyof typeof demoData.kilnInfo], ); } break; 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; case 'fan': // data = demoData.fan; break; case 'gas': // data = demoData.gas; break; case 'kiln-top': // data = demoData.kilnTop; break; case 'kiln-bottom': // data = demoData.kilnBottom; break; default: // data = 'You are connected!'; break; } // console.log("sendMsg: ", ws); // ws.emit("message", JSON.stringify(data)); ws.send(JSON.stringify({ type, data })); }