在Java中,可以使用Socket類來實現端口轉發。以下是一個簡單的示例代碼,演示了如何將本地的一個端口轉發到另一個遠程主機的端口。
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class PortForwardingExample {
public static void main(String[] args) {
int localPort = 12345; // 本地端口
String remoteHost = "example.com"; // 遠程主機
int remotePort = 80; // 遠程端口
try {
// 創建本地服務器套接字
ServerSocket serverSocket = new ServerSocket(localPort);
System.out.println("等待客戶端連接...");
while (true) {
// 監聽客戶端連接
Socket clientSocket = serverSocket.accept();
System.out.println("客戶端連接成功!");
// 創建與遠程主機的套接字連接
Socket remoteSocket = new Socket(remoteHost, remotePort);
// 創建線程進行數據轉發
Thread inputThread = new Thread(new ForwardingHandler(clientSocket.getInputStream(), remoteSocket.getOutputStream()));
Thread outputThread = new Thread(new ForwardingHandler(remoteSocket.getInputStream(), clientSocket.getOutputStream()));
inputThread.start();
outputThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 數據轉發處理器
static class ForwardingHandler implements Runnable {
private final InputStream input;
private final OutputStream output;
public ForwardingHandler(InputStream input, OutputStream output) {
this.input = input;
this.output = output;
}
@Override
public void run() {
byte[] buffer = new byte[4096];
int bytesRead;
try {
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上述代碼創建一個ServerSocket對象來監聽本地指定端口上的連接。當有客戶端連接成功后,會通過Socket對象與遠程主機建立連接。然后,創建兩個線程來分別處理從客戶端到遠程主機和從遠程主機到客戶端的數據轉發。數據轉發處理器實現了Runnable接口,通過讀取輸入流的數據,并將其寫入輸出流來實現轉發。