tianji/src/server/udp/server.ts
2024-01-06 00:16:43 +08:00

31 lines
768 B
TypeScript

import dgram from 'dgram';
import { recordServerStatus } from '../model/serverStatus';
import { logger } from '../utils/logger';
export function initUdpServer(port: number) {
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
logger.info(`Init error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
try {
const raw = String(msg);
const json = JSON.parse(String(msg));
logger.info('[UDP] recevice tianji report:', raw, 'info', rinfo);
recordServerStatus(json);
} catch (err) {}
});
server.on('listening', () => {
const address = server.address();
logger.info(`UDP Server is listening: ${address.address}:${address.port}`);
});
server.bind(port);
}