Using sockets in Java with a proxy

生来就可爱ヽ(ⅴ<●) 提交于 2020-02-02 05:35:08

问题


I'm writing a very simple transport simulation (please don't ask why I use this approach, it's not really the point of my question).

I have three threads running (although you could consider them as seperate programs). One as a client, one as a server, and one as a proxy.

The first is used as the client, and the main code for that is given here:

try {
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(InetAddress.getLocalHost(), 4466));
    Socket socket = new Socket(proxy);
    InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getLocalHost(), 4456);
    socket.connect(socketAddress);

    // send data
    for (String straat : straten) {
        socket.getOutputStream().write(straat.getBytes());
    }

    socket.getOutputStream().flush();
    socket.getOutputStream().close();
    socket.close();

} catch (Exception e) {
    e.printStackTrace();
}

The second is the server side, given here:

public void run() {
    try {
        ServerSocket ss = new ServerSocket(4456);
        Socket s = ss.accept();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(s.getInputStream()));

        String incoming;
        while ((incoming = in.readLine()) != null) {
            panel.append(incoming + "\n");
        }

        panel.append("\n");
        s.getInputStream().close();
        s.close();
        ss.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

And then there's the proxy-thread:

public void run() {
    try {
        ServerSocket ss = new ServerSocket(4466);
        Socket s = ss.accept();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(s.getInputStream()));

        panel.append(verzenderId + "\n");

        String incoming;
        while ((incoming = in.readLine()) != null) {
            panel.append(incoming + "\n");
        }

        panel.append("\n");
        s.getInputStream().close();
        s.close();
        ss.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

Somehow, this won't work. The message is sent directly to the server, and the proxy doesn't receive any socket request.

How can I make this work so that port 4466 becomes a proxy for the communication between the client-thread and the server-thread?

The goal is to make this socket between the client and the server to become an SSLSocket, so that the proxy can't read anything that goes over it. Therefore, setting up two sockets, one between the client and the proxy and one between the proxy and the server, is not the solution I'm looking for.

Thanks a lot in advance.

来源:https://stackoverflow.com/questions/6047815/using-sockets-in-java-with-a-proxy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!