VintageBigBlue.org

 
Nov 11, 2018

When connecting to a socket it is often best to specify a timeout. The default timeout can have a user waiting for an excessive period of time and especially in an intranet environment where any connect attempt should happen really fast or there is something wrong that it will cause an eventual fail anyway.

// This socket connection attempt will throw an exception if it
// does not succeed within 5 seconds.
try {
    InetAddress iAddr = InetAddress.getByName("www.google.com");
    int tcpPort = 80;
    SocketAddress sockaddr = new InetSocketAddress(iAddr, tcpPort);
// This creates an un-bound socket
    Socket sock = new Socket();
// Here we go - try to connect
    sock.connect(sockaddr,5000);     // timeout is in milliseconds
    System.out.println("We made it here, we must have suceeded.") ;
} catch (NoRouteToHostException e) {
    System.out.println("The network path to the host is somehow interrupted") ;
} catch (UnknownHostException e) {
    System.out.println("The host does not exist or your DNS failure") ;
} catch (SocketTimeoutException e) {
    System.out.println("Could not connect in 5 seconds") ;
} catch (IOException e) {
    System.out.println("IO Exception " + e.toString() ;
}
}

Contact Us
This Site's Privacy Policy
Google's privacy policies