2023-09-30 16:01:43 +00:00
|
|
|
import dgram from 'dgram';
|
2023-10-31 16:02:52 +00:00
|
|
|
import { recordServerStatus } from '../model/serverStatus';
|
2024-01-05 16:16:43 +00:00
|
|
|
import { logger } from '../utils/logger';
|
2023-09-30 16:01:43 +00:00
|
|
|
|
|
|
|
export function initUdpServer(port: number) {
|
|
|
|
const server = dgram.createSocket('udp4');
|
|
|
|
|
|
|
|
server.on('error', (err) => {
|
2024-01-05 16:16:43 +00:00
|
|
|
logger.info(`Init error:\n${err.stack}`);
|
2023-09-30 16:01:43 +00:00
|
|
|
server.close();
|
|
|
|
});
|
|
|
|
|
|
|
|
server.on('message', (msg, rinfo) => {
|
|
|
|
try {
|
|
|
|
const raw = String(msg);
|
|
|
|
const json = JSON.parse(String(msg));
|
2023-10-03 12:45:00 +00:00
|
|
|
|
2024-01-05 16:16:43 +00:00
|
|
|
logger.info('[UDP] recevice tianji report:', raw, 'info', rinfo);
|
2023-10-03 12:45:00 +00:00
|
|
|
|
2023-10-31 16:02:52 +00:00
|
|
|
recordServerStatus(json);
|
2023-09-30 16:01:43 +00:00
|
|
|
} catch (err) {}
|
|
|
|
});
|
|
|
|
|
|
|
|
server.on('listening', () => {
|
|
|
|
const address = server.address();
|
2024-01-05 16:16:43 +00:00
|
|
|
logger.info(`UDP Server is listening: ${address.address}:${address.port}`);
|
2023-09-30 16:01:43 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
server.bind(port);
|
|
|
|
}
|