98 lines
1.9 KiB
TypeScript
98 lines
1.9 KiB
TypeScript
import _ from "lodash"
|
|
import { type udp } from "bun"
|
|
import type { UDPDataType } from "./udp";
|
|
import { None, Some, type Option } from "ts-results-es";
|
|
import { z } from "zod";
|
|
|
|
// Bun Data Type
|
|
interface BinaryTypeList {
|
|
arraybuffer: ArrayBuffer;
|
|
buffer: Buffer;
|
|
uint8array: Uint8Array;
|
|
}
|
|
type BinaryType = keyof BinaryTypeList;
|
|
|
|
const receivedData: Map<string, Array<{
|
|
body: udp.Data,
|
|
port: number,
|
|
date: string
|
|
}>> = new Map()
|
|
|
|
const udpServer = await Bun.udpSocket({
|
|
port: 33000,
|
|
socket: {
|
|
data(
|
|
_socket: udp.Socket<BinaryType>,
|
|
data: BinaryTypeList[BinaryType],
|
|
port: number,
|
|
address: string,
|
|
) {
|
|
// Add Received Data
|
|
let arrayData = receivedData.get(address)
|
|
if (_.isUndefined(arrayData)) {
|
|
|
|
} else {
|
|
receivedData.set(address, [])
|
|
arrayData.push({
|
|
body: data,
|
|
port: port,
|
|
date: new Date().toUTCString()
|
|
})
|
|
}
|
|
}
|
|
}
|
|
})
|
|
|
|
function port(): number {
|
|
return udpServer.port
|
|
}
|
|
|
|
function lastestData(address: string): Option<UDPDataType<udp.Data>> {
|
|
if (!z.string().ip().safeParse(address).success) {
|
|
return None
|
|
}
|
|
|
|
const arrayData = receivedData.get(address)
|
|
if (_.isUndefined(arrayData)) {
|
|
return None
|
|
}
|
|
|
|
const data = arrayData.pop()
|
|
if (_.isUndefined(data)) {
|
|
return None
|
|
}
|
|
|
|
return Some({
|
|
address: address,
|
|
body: data.body,
|
|
port: data.port,
|
|
date: data.date,
|
|
})
|
|
}
|
|
|
|
function oldestData(address: string): Option<UDPDataType<udp.Data>> {
|
|
if (!z.string().ip().safeParse(address).success) {
|
|
return None
|
|
}
|
|
|
|
const arrayData = receivedData.get(address)
|
|
if (_.isUndefined(arrayData)) {
|
|
return None
|
|
}
|
|
|
|
const data = arrayData.shift()
|
|
if (_.isUndefined(data)) {
|
|
return None
|
|
}
|
|
|
|
return Some({
|
|
address: address,
|
|
body: data.body,
|
|
port: data.port,
|
|
date: data.date,
|
|
})
|
|
}
|
|
|
|
export { port, lastestData, oldestData }
|
|
|