81 lines
2.1 KiB
TypeScript
81 lines
2.1 KiB
TypeScript
import { resolve } from "path";
|
|
import Tinypool from "tinypool";
|
|
import type { UDPReceiveProcotol, UDPSendProtocol } from "./udpProtocol";
|
|
import type { udp } from "bun";
|
|
import { Option } from "ts-results-es";
|
|
|
|
const SERVER_PATH = resolve(__dirname, "./udpServer.ts")
|
|
const CLIENT_PATH = resolve(__dirname, "./udpClient.ts")
|
|
|
|
export type UDPBodyType = (
|
|
udp.Data |
|
|
UDPSendProtocol.CmdPackage |
|
|
UDPSendProtocol.DataPackage |
|
|
UDPReceiveProcotol.ReadPackage |
|
|
UDPReceiveProcotol.WritePackage
|
|
)
|
|
|
|
type UDPDataType<T extends UDPBodyType = UDPBodyType> = {
|
|
address: string,
|
|
body: T,
|
|
port: number,
|
|
date?: string,
|
|
}
|
|
|
|
|
|
const udpClientsPool = new Tinypool({
|
|
filename: CLIENT_PATH,
|
|
workerData: {}
|
|
})
|
|
|
|
const udpServerPool = new Tinypool({
|
|
filename: SERVER_PATH,
|
|
workerData: {},
|
|
maxThreads: 1,
|
|
minThreads: 1,
|
|
})
|
|
|
|
export namespace udpServer {
|
|
|
|
export async function port(): Promise<number> {
|
|
return udpServerPool.run(null, { name: "port" })
|
|
}
|
|
|
|
export async function lastestData(address: string): Promise<Option<UDPDataType<udp.Data>>> {
|
|
return udpServerPool.run(address, { name: "lastestData" })
|
|
}
|
|
|
|
export async function oldestData(address: string): Promise<Option<UDPDataType<udp.Data>>> {
|
|
return udpServerPool.run(address, { name: "oldestData" })
|
|
}
|
|
|
|
}
|
|
|
|
export namespace udpClient {
|
|
|
|
export async function sendString(data: string, port: number, address: string): Promise<boolean> {
|
|
return udpClientsPool.run({
|
|
body: data,
|
|
port: port,
|
|
address: address
|
|
} as UDPDataType<string>, { name: "sendString" })
|
|
}
|
|
|
|
export async function sendUint8Array(data: Uint8Array, port: number, address: string): Promise<boolean> {
|
|
return udpClientsPool.run({
|
|
body: data,
|
|
port: port,
|
|
address: address
|
|
} as UDPDataType<Uint8Array>, { name: "sendUint8Array" })
|
|
}
|
|
|
|
export async function sendBunData(data: udp.Data, port: number, address: string): Promise<boolean> {
|
|
return udpClientsPool.run({
|
|
body: data,
|
|
port: port,
|
|
address: address
|
|
} as UDPDataType<udp.Data>, { name: "sendUint8Array" })
|
|
}
|
|
}
|
|
export type { UDPDataType }
|