>  기사  >  웹 프론트엔드  >  Node.js를 사용하여 스크래치 프록시 서버를 구축하는 방법

Node.js를 사용하여 스크래치 프록시 서버를 구축하는 방법

WBOY
WBOY원래의
2024-07-17 14:23:08493검색

프록시 서버의 작동 방식과 인터넷을 통해 데이터를 제공하는 방식이 궁금하실 것입니다. 이 블로그에서는 핵심 NodeJ를 사용하여 프록시 서버를 구현하려고 합니다. 이미 NodeJ와 함께 제공되는 net이라는 핵심 NodeJs 패키지를 사용하여 이를 구현했습니다.

프록시 작동 방식

프록시 서버는 클라이언트와 서버 사이의 에이전트입니다.

클라이언트가 서버에 요청을 보내고 대상 프록시로 전달됩니다.
섬기는 사람. 대상 프록시 서버가 요청을 처리하고 보냅니다.
메인 서버로 전송되고 메인 서버는
에 백 요청을 보냅니다. 프록시 서버와 프록시 서버가 클라이언트에 요청을 보냅니다.

preview image

프록시 서버 설정

프로그래밍을 시작하기 전에는 소켓과 NodeJ에 대해 거의 알지 못합니다. 소켓이 무엇인지, 어떻게 작동하는지 알고 있습니다.
NodeJ에는 프록시 서버를 구현하는 두 가지 방법이 있습니다. 첫 번째는 사용자 정의 방법이고 두 번째는 내장형입니다. 둘 다 이해하기 쉽습니다.

프록시 서버를 테스트하려면 로컬 컴퓨터에서 로컬 HTTP 서비스를 실행한 다음 호스트 컴퓨터를 대상으로 지정할 수 있습니다.

  • 이제 넷 패키지를 정의한 후 대상 서버와 포트 번호를 작성하겠습니다.
const net = require('net');

// Define the target host and port
const targetHost = 'localhost'; // Specify the hostname of the target server. For Ex: (12.568.45.25)
const targetPort = 80; // Specify the port of the target server
  • TCP 서버 생성 및 청취.
const server = net.createServer((clientSocket) => {

});

// 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}`);
});
  • net 패키지를 사용하여 서버를 만들었습니다. 이는 ProxyPort 변수를 사용하여 정의한 대로 포트 번호 3000을 실행하는 TCP 서버입니다. 서버가 시작되면 역방향 프록시 서버가 포트 3000에서 수신 중이라는 메시지가 콘솔에 표시됩니다.
  • 클라이언트가 프록시 서버에 연결을 시도하면 createServer 내부에 있는 콜백 함수가 실행됩니다.
  • 서버 함수 콜백에는 clientSocket 매개변수가 하나 있는데, 이는 연결을 위해 수신한 사용자 연결입니다.

  • 사용자로부터 데이터 수락 및 수신

const targetHost = 'localhost'; // Specify the hostname of the target server. For Ex: (12.568.45.25)
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
    net.createConnection({host: targetHost, port: targetPort}, () => {

        // When data is received from the client, write it to the target server
        clientSocket.on("data", (data) => {
            targetSocket.write(data);
        });

        // When data is received from the target server, write it back to the client
        targetSocket.on("data", (data) => {
            clientSocket.write(data);
        });
    });
});
  • 클라이언트가 프록시 서버에 연결을 시도할 때 createConnection 생성을 사용하여 서버에 대한 임시 연결을 생성합니다.
  • createServer에는 2개의 인수가 있습니다.
    • 이 경우 연결하려는 첫 번째 호스트는 targetHost 변수에 정의된 서버 호스트에 연결해야 합니다.
    • 이 경우 연결하려는 두 번째 포트는 targetPort 변수에 정의된 서버 포트에 연결해야 합니다.
  • 이제 사용자가 데이터를 보내면 이 데이터를 서버에 전달합니다. 이 코드를 사용하여
 clientSocket.on("data", (data) => {
     targetSocket.write(data);
 });
  • 그런 다음 서버는 이 코드를 사용하여 이 데이터를 사용자에게 보낼 데이터를 보냅니다.
  targetSocket.on("data", (data) => {
      clientSocket.write(data);
  });
  • 축하합니다! 프록시 서버를 성공적으로 만들었습니다.

오류 처리

프록시 서버의 기능을 탐색하는 것은 흥미롭지만 안정성을 보장하려면 예상치 못한 문제를 적절하게 처리할 수 있는 강력한 오류 처리 방법이 필요합니다. 이러한 유형의 오류를 처리하기 위해 오류라는 이벤트가 있습니다. 구현이 매우 쉽습니다.

    const server = net.createServer((clientSocket) => {
     // Establish a connection to the target host
     const targetSocket = net.createConnection({host: targetHost,port: targetPort}, () => {

       // Handle errors when connecting to the target server
       targetSocket.on('error', (err) => {
         console.error('Error connecting to target:', err);
         clientSocket.end(); // close connection
       });

       // Handle errors related to the client socket
       clientSocket.on('error', (err) => {
         console.error('Client socket error:', err);
         targetSocket.end(); // close connection
       });
     });
   });
  • 오류가 발생하면 오류를 위로한 후 연결을 종료합니다.

모든 코드

  • 원하는 대로 호스트 이름과 포트 번호를 바꾸세요.
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}`);
});

구축 방법

클라이언트와 서버 연결의 복잡성을 줄이기 위해 메소드 파이프가 내장되어 있습니다. 이 구문을 대체하겠습니다

// Handle errors when connecting to the target server
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);
});

이 구문에

// Pipe data from the client to the target
clientSocket.pipe(targetSocket);

// When data is received from the client, write it to the target server
targetSocket.pipe(clientSocket);

여기에 모든 코드가 있습니다

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}`);
});

작동하는 프록시 서버!

GitHub avinashtare에서 팔로우하세요. 감사합니다.

위 내용은 Node.js를 사용하여 스크래치 프록시 서버를 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.