import { WebSocket, WebSocketServer } from 'ws'; import demoData from './demo.json'; const wss = new WebSocketServer({ port: 9800 }); const frequency = 3; // 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, 'base-info'); 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 = 'base-info' | 'fan' | 'gas' | 'kiln-top' | 'kiln-bottom'; function sendMsg(ws: WebSocket, type: MsgType) { let data: any; switch (type) { case 'base-info': data = demoData.baseInfo; 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(data)); }