bqui56
bqui56

Reputation: 2111

Why doesn't this program end?

I was expecting to receive the HTTP response and then for the Socket to be closed but it just sits there never ending after the page is returned. I'm assuming it is to do with the Scanner; why doesn't this program ever end?

public class PingHost {
   public static void main(String[] args) throws Exception {
      Socket s = new Socket("www.google.com", 80);
      DataOutputStream out = new DataOutputStream(s.getOutputStream());
      out.writeBytes("GET / HTTP/1.1\n\n");
      Scanner sc = new Scanner(s.getInputStream());
      while (sc.hasNext())
         System.out.println(sc.nextLine());
      System.out.println("never gets to here");
      s.close();
   }
}

Upvotes: 1

Views: 104

Answers (2)

tomwesolowski
tomwesolowski

Reputation: 956

It's a stream, so Java can't predict when and where input is over. You need to specify some "ending token", find it and stop reading.

while (sc.hasNextLine()) {
      String str = sc.nextLine();
      System.out.println(str);
      if(str.endsWith("</HTML>")) break;
}

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

From the javadoc

This method may block while waiting for input to scan

Upvotes: 4

Related Questions