tcplexer/tcplexer.ts

75 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-06-24 23:11:49 -05:00
#!/usr/bin/env -S deno run --allow-net --allow-env
2022-06-24 19:19:51 -05:00
import { iterateReader } from "https://deno.land/std@0.145.0/streams/conversion.ts";
const clients: Set<Deno.Conn> = new Set();
(async () => {
try {
2022-06-24 23:11:49 -05:00
const sourcePort = parseInt(Deno.env.get("SOURCE_PORT") || "") || 0;
const sourceSockOpts = {
port: sourcePort,
};
const sourceListener = Deno.listen(sourceSockOpts);
console.info(
"Listening for source connections on port",
(sourceListener.addr as Deno.NetAddr).port,
);
2022-06-24 19:19:51 -05:00
for await (const source of sourceListener) {
console.info("Source connected from", source.remoteAddr);
for await (const packet of iterateReader(source)) {
clients.forEach((client, _v2, _set) =>
client.write(packet).catch(() => {
console.log(`Client disconnected from`, client.remoteAddr);
clients.delete(client);
})
);
}
console.info(`Source disconnected from`, source.remoteAddr);
}
} catch (err) {
2022-06-24 23:11:49 -05:00
console.error("Error listening for source TCP connections:", err);
Deno.exit(1);
2022-06-24 19:19:51 -05:00
}
})();
(async () => {
try {
2022-06-24 23:11:49 -05:00
const clientPort = parseInt(Deno.env.get("CLIENT_PORT") || "") || 0;
const clientSockOpts = {
port: clientPort,
};
const clientsListener = Deno.listen(clientSockOpts);
console.info(
"Listening for client connections on port",
(clientsListener.addr as Deno.NetAddr).port,
);
2022-06-24 19:19:51 -05:00
while (true) {
try {
const conn = await clientsListener.accept();
console.log("Client connected from", conn.remoteAddr);
clients.add(conn);
} catch (err) {
console.error("Error accepting client connection:", err);
}
}
} catch (err) {
console.error("Error listening for TCP connections on port 8081:", err);
}
})();
2022-06-24 23:11:49 -05:00
/* stdin
(async () => {
for await (const packet of iterateReader(Deno.stdin)) {
clients.forEach((client, _v2, _set) =>
client.write(packet).catch(() => {
console.log(`Client disconnected from`, client.remoteAddr);
clients.delete(client);
})
);
}
})();
*/