1

我正在尝试创建一个 Java 程序作为代理来查看来自传入源的数据包以进行调试。为此,我创建了一个简单的 Java 服务器应用程序并在设备上编辑了我的主机文件。到目前为止一切正常,(甚至是我的 Relay 类文件),但我正试图将其变成一个成熟的代理。如何合并元素以将数据发送到服务器,并将响应发送回客户端?有点像中间人类型的东西。

import java.net.*;
import java.io.*;
import org.ini4j.Ini;

public class RelayMultiClient extends Thread {
    private Socket socket = null;
    Socket relay = null;

    public RelayMultiClient(Socket socket) {
    super("RelayMultiClient");
    this.socket = socket;
    }

    public void run() {

    try {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
                    new InputStreamReader(
                    socket.getInputStream()));
        if(Relay.max_clients == Relay.connected_clients) {
            //There are too many clients on the server.
            System.out.println("Connection refused from " + socket.getRemoteSocketAddress() + ": Too many clients connected!");
            out.close();
            in.close();
            socket.close();
        }
        else {
            Ini ini = new Ini(new File("settings.ini"));
            Relay.connected_clients++;
            System.out.println("Connection from client " + socket.getRemoteSocketAddress() + " established. Clients Connected: " + Relay.connected_clients);
            while (in.readLine() != null) {
                //Send data to the server
                //Receive data from server and send back to client
            }
            System.out.println("Connection from client " + socket.getRemoteSocketAddress() + " lost.");
            Relay.connected_clients--;
            out.close();
            in.close();
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    }
}

谢谢,克里斯

PS:我不是在尝试获取 HTTP 数据,而是在尝试从我创建的游戏中获取数据。我不知道这种类型的数据是否需要任何额外的处理。

4

1 回答 1

3

如何合并元素以将数据发送到服务器,并将响应发送回客户端?

尝试以下示例作为基本代理:

public class Proxy {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(1230); // proxy port
        Socket socket = serverSocket.accept();
        Socket relay = new Socket("localhost", 1234); // server address
        new ProxyThread(relay.getInputStream(), socket.getOutputStream()).start();
        new ProxyThread(socket.getInputStream(), relay.getOutputStream()).start();
    }
}

class ProxyThread extends Thread {
    private InputStream inputStream;
    private OutputStream outputStream;

    ProxyThread(InputStream inputStream, OutputStream outputStream) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
    }

    public void run() {
        try {
            int i;
            while ((i = inputStream.read()) != -1) {
                outputStream.write(i);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

它缺乏适当的异常处理,仅展示基本思想。

于 2013-09-07T19:03:31.160 回答