开发者

Using sockets in Java with a proxy

开发者 https://www.devze.com 2023-03-06 15:42 出处:网络
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'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 开发者_JAVA技巧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.

0

精彩评论

暂无评论...
验证码 换一张
取 消