首页  >  文章  >  web前端  >  如何使用 Node.js 构建临时代理服务器

如何使用 Node.js 构建临时代理服务器

WBOY
WBOY原创
2024-07-17 14:23:08493浏览

您可能对代理服务器如何工作以及它们如何通过互联网提供数据感到好奇。在这篇博客中,我将使用核心 NodeJs 实现一个代理服务器。我使用 NodeJs 附带的名为 net 的核心 NodeJs 包实现了这一点。

代理如何工作

代理服务器是客户端和服务器之间的代理。当

客户端向服务器发送请求,该请求被转发到目标代理
服务器。目标代理服务器处理请求并发送
到主服务器,主服务器将返回请求发送到
代理服务器,代理服务器将请求发送给客户端。

preview image

设置代理服务器

在开始编程之前,您对socket和NodeJs知之甚少。您知道什么是socket以及它们是如何工作的。
在 NodeJs 中有两种方法来实现代理服务器。首先是自定义方法,第二是内置方法。两者都很容易理解。

要测试您的代理服务器,您可以在本地计算机上运行本地 HTTP 服务器,然后定位主机。

  • 现在,我将定义 net 包,然后写入目标服务器和端口号。
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 包创建了一个服务器。它是一个 TCP 服务器,运行端口号 3000,正如我们在使用 proxyPort 变量中定义的那样。如果服务器启动,它将在控制台上显示反向代理服务器正在侦听端口 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);
        });
    });
});
  • 当客户端尝试连接代理服务器时,我们将使用 create 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}`);
});

构建方法

为了降低客户端和服务器连接的复杂性,我们有内置的方法pipe。我将替换这个语法

// 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