0

I have an android device hosting an HTTP server and is NATed(behind router). I want to access it from a public server which is not NATed. I run a HTTP server on android device at port 8080 in a thread and after some time, I launch a client thread which tries to connect to remote public server from local port number 8080 on android. For some reason, android client won't connect after I start server on port 8080. Nor does it yield any exception. Here is my code:

Thread server = new Thread(new Runnable() {
public void run() {
    super.run();

    try {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress("192.168.1.102", 8080));

        while(isRunning){
            try {
                System.out.println("Listening for new connection");
                Socket socket = serverSocket.accept();
                System.out.println("incoming connection accepted");
                new Thread(new ConnectionHandler(socket)).start();    
            } catch (IOException e) {
                e.printStackTrace();
            }                             
        }
        serverSocket.close();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
}
});
server.start();



// sleep several seconds before launch of client
Thread.currentThread().sleep(5 * 1000);


Thread client = new Thread(new Runnable() {
public void run() {
    super.run();
    try {
        /* .. */
        Inet4Address localaddr = (Inet4Address) InetAddress
                .getByName("192.168.1.102");
        // Inet4Address remoteaddr = (Inet4Address)
        // InetAddress.getByName("122.176.73.10");
        System.out.println("connecting to 122.176.73.10");

        Socket socket = new Socket();

        socket.setReuseAddress(true);
        System.out.println("[Client]socket.isBound():" + socket.isBound());
        socket.bind(new InetSocketAddress("192.168.1.102", 8080));

        for (int i = 1; i < 5; i++) {
            try {
                socket.connect(new InetSocketAddress("122.176.73.10", 4040));
                System.out.println("connected to 122.176.73.10");
                break;
            } catch (Exception e) {
                System.out.println("[Client]fail to connect ");
                Thread.currentThread().sleep(i * 2 * 1000);
            }
        }
    }
}
});
client.start();
rohitverma
  • 767
  • 2
  • 9
  • 14

1 Answers1

0

A port number can't be used to both listen for incoming connections and make an outgoing connection. Your listening socket on 8080 prevents anything else using that port.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • It is claimed to be working here: http://ramonli.blogspot.in/2012/03/tcp-hole-punching-how-to-establish-tcp.html – rohitverma Feb 10 '13 at 09:59