I’m requesting a webpage with sockets like this:
Socket sock = null;
PrintWriter out = null;
BufferedReader in = null;
try {
sock = new Socket( "www.overvprojects.nl", 80 );
out = new PrintWriter( sock.getOutputStream(), true );
in = new BufferedReader( new InputStreamReader( sock.getInputStream() ) );
} catch ( UnknownHostException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
out.println( "GET /ip.php HTTP/1.1" );
out.println( "Host: www.overvprojects.nl" );
out.println( "" );
out.flush();
String buf = "";
while ( buf != null )
{
try {
buf = in.readLine();
} catch ( IOException e ) {
e.printStackTrace();
}
if ( buf != null && Pattern.matches( "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$", buf ) ) {
ipText.setText( buf );
break;
}
}
try {
in.close();
out.close();
sock.close();
} catch ( IOException e ) {
e.printStackTrace();
}
However, the program seems to wait until the connection times out. I’ve debugged the loop and I’m absolutely sure break is called, yet the UI doesn’t update until the connection is terminated. (This takes over 10 seconds.) After that the IP is visible, so I’m sure break has been called at some point. I’ve also tried using the website http://www.whatismyip.org instead and that does finish within two seconds.
You need to check the content length header returned by the server. Only read that many bytes then close the connection after that.
You are waiting until the server closes the connection which is why it is taking 20 seconds.