首頁 > web前端 > js教程 > 主體

如何使用 Node.js 建立臨時代理伺服器

WBOY
發布: 2024-07-17 14:23:08
原創
491 人瀏覽過

您可能對代理伺服器如何運作以及它們如何透過網路提供資料感到好奇。在這篇部落格中,我將使用核心 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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!