How Proxy Server Works With Node Js practical
// Require the 'net' module for TCP networking
const net = require('net');
// Define the target host and port
const targetHost = 'localhost'; // Specify the hostname of the target server
const targetPort = 80; // Specify the port of the target server
// Create a TCP server
const server = net.createServer((clientSocket) => {
// Establish a connection to the target host
const targetSocket = net.createConnection({ host: targetHost, port: targetPort }, () => {
// When data is received from the target server, write it back to the client
targetSocket.on("data", (data) => {
clientSocket.write(data);
});
// When data is received from the client, write it to the target server
clientSocket.on("data", (data) => {
targetSocket.write(data);
});
});
// Handle errors when connecting to the target server
targetSocket.on('error', (err) => {
console.error('Error connecting to target:', err);
clientSocket.end();
});
// Handle errors related to the client socket
clientSocket.on('error', (err) => {
console.error('Client socket error:', err);
targetSocket.end();
});
});
// Start listening for incoming connections on the specified port
const proxyPort = 3000; // Specify the port for the proxy server
server.listen(proxyPort, () => {
console.log(`Reverse proxy server is listening on port ${proxyPort}`);
});
Another METHOD using pipe
const net = require('net');
// Define the target host and port
const targetHost = 'localhost';
const targetPort = 80;
// Create a TCP server
const server = net.createServer((clientSocket) => {
// Establish a connection to the target host
const targetSocket = net.createConnection({ host: targetHost, port: targetPort }, () => {
// Pipe data from the client to the target
clientSocket.pipe(targetSocket);
// Pipe data from the target to the client
targetSocket.pipe(clientSocket);
});
// Handle errors
targetSocket.on('error', (err) => {
console.error('Error connecting to target:', err);
clientSocket.end();
});
clientSocket.on('error', (err) => {
console.error('Client socket error:', err);
targetSocket.end();
});
});
// Start listening for incoming connections
const proxyPort = 3000;
server.listen(proxyPort, () => {
console.log(`Reverse proxy server is listening on port ${proxyPort}`);
});
Comments
Post a Comment