abstract server a bit better

This commit is contained in:
DavidVentura
2024-01-31 11:56:33 +01:00
parent 0b2ac1a118
commit 9d671f18c9
2 changed files with 32 additions and 24 deletions
+31 -11
View File
@@ -2,7 +2,6 @@ import { createSocket, RemoteInfo } from "node:dgram";
import { Commands, CommandsByValue } from "./datatypes.js";
import { handle_P2PAlive, handle_PunchPkt, handle_P2PRdy, handle_Drw, notImpl, noop } from "./handlers.js";
import { hexdump } from "./hexdump.js";
import { SendDevStatus } from "./impl.js";
import EventEmitter from "node:events";
export type Session = {
@@ -22,10 +21,32 @@ type opt = {
ansi: boolean;
};
type msgCb = (session: Session, msg: Buffer, rinfo: RemoteInfo, options: opt) => void;
type msgCb = (
session: Session,
handlers: Record<keyof typeof Commands, PacketHandler>,
msg: Buffer,
rinfo: RemoteInfo,
options: opt,
) => void;
type connCb = (session: Session) => void;
export const makeSession = (cb: msgCb, connCb: connCb, options: opt): Session => {
const handleIncoming: msgCb = (session, handlers, msg, rinfo, options) => {
const ab = new Uint8Array(msg).buffer;
const dv = new DataView(ab);
const cmd = CommandsByValue[dv.readU16()];
if (options.debug) {
console.log(`<< ${cmd}`);
console.log(hexdump(msg.buffer, { ansi: options.ansi, ansiColor: 1 }));
}
handlers[cmd](session, dv, rinfo);
session.lastReceivedPacket = Date.now();
};
export const makeSession = (
handlers: Record<keyof typeof Commands, PacketHandler>,
connCb: connCb,
options: opt,
): Session => {
const sock = createSocket("udp4");
sock.on("error", (err) => {
@@ -33,7 +54,7 @@ export const makeSession = (cb: msgCb, connCb: connCb, options: opt): Session =>
sock.close();
});
sock.on("message", (msg, rinfo) => cb(session, msg, rinfo, options));
sock.on("message", (msg, rinfo) => handleIncoming(session, handlers, msg, rinfo, options));
sock.on("listening", () => {
const address = sock.address();
@@ -43,7 +64,8 @@ export const makeSession = (cb: msgCb, connCb: connCb, options: opt): Session =>
});
const RECV_PORT = 49512; // important?
const BCAST_IP = "192.168.1.255";
//const BCAST_IP = "192.168.1.255";
const BCAST_IP = "192.168.40.101";
const SEND_PORT = 32108;
sock.bind(RECV_PORT);
@@ -76,20 +98,18 @@ export const makeSession = (cb: msgCb, connCb: connCb, options: opt): Session =>
export const Handlers: Record<keyof typeof Commands, PacketHandler> = {
PunchPkt: handle_PunchPkt,
P2PAlive: handle_P2PAlive,
P2pRdy: handle_P2PRdy,
DrwAck: noop,
Drw: handle_Drw,
Close: notImpl,
LanSearchExt: notImpl,
LanSearch: notImpl,
P2PAlive: handle_P2PAlive,
P2PAliveAck: notImpl,
Hello: notImpl,
P2pRdy: handle_P2PRdy,
P2pReq: notImpl,
LstReq: notImpl,
DrwAck: noop,
Drw: handle_Drw,
// From CSession_CtrlPkt_Proc, incomplete
PunchTo: notImpl,
HelloAck: notImpl,
RlyTo: notImpl,