Search code examples
javasocketsnio

connect(localhost) throws exception, connect(private address) blocks


The following code throws an exception when I tried to run it with a localhost 172.0.0.1: java.net.ConnectException: Connection refused: connect

channel = SocketChannel.open();
//172.0.0.1 is a non-existing server 
channel.connect(new InetSocketAddress("172.0.0.1", 4342));

However, the following code blocks until timeout when I ran it with a private address:

channel = SocketChannel.open();
//192.168.0.1 is a non-existing server 
channel.connect(new InetSocketAddress("192.168.0.1", 4342));

May I ask why connecting to a localhost would cause connect to throw an exception while connecting to a private address would block?

I ask this because I want the connect() to block while I bring up the localhost server and the connect() would automatically connect to the server when the server is up.

Is there a way to make connect() to block on localhost address?

Thanks!


Solution

  • Connection refused means that the destination server actively refused the connection because there is no server listening on that port.

    Timeout occurs when client receives no response from server, e.g. the server doesn't exist at all, traffic being blocked by some firewall etc.

    There is nothing like try connecting and send me response when the port becomes occupied. You have to implement retries on client side.