Skip to content

Instantly share code, notes, and snippets.

@mekb-turtle
Created September 9, 2022 13:05
Show Gist options
  • Save mekb-turtle/184ee6ee8761fe7982f7b2add80f664f to your computer and use it in GitHub Desktop.
Save mekb-turtle/184ee6ee8761fe7982f7b2add80f664f to your computer and use it in GitHub Desktop.
Simple Node.js proxy
#!/usr/bin/env node
const net = require("net");
const serverClientHost = "192.168.88.79"; // P->S
const serverClientPort = 22;
const proxyServerPort = 1337; // C->S
const proxyServer = new net.Server();
proxyServer.on("connection", (socket) => {
console.log("[C-P] new connection");
console.log(socket.address());
let serverClient = new net.Socket();
let queue = [];
let popQueue = () => {
if (!serverClient.connecting && !serverClient.destroyed) {
if (queue.length > 0) {
serverClient.write(queue.pop());
}
}
}
serverClient.on("ready", () => {
console.log("[P-S] connected");
popQueue();
});
socket.on("data", data => {
console.log("[C->P->S] write data");
queue.push(data);
popQueue();
});
serverClient.on("data", data => {
console.log("[S->P->C] write data");
if (!socket.destroyed) return;
socket.write(data);
});
socket.on("end", () => {
console.log("[C-P] connection closed");
socket.destroy();
serverClient.destroy();
});
serverClient.on("end", () => {
console.log("[P-S] connection closed");
socket.destroy();
serverClient.destroy();
});
socket.on("error", (err) => {
console.log("[C-P] connection error");
console.log(err);
socket.destroy();
serverClient.destroy();
});
serverClient.on("error", (err) => {
console.log("[P-S] connection error");
console.log(err);
socket.destroy();
serverClient.destroy();
});
});
proxyServer.listen(proxyServerPort, () => {
console.log("proxy listening on port", proxyServerPort);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment