简体   繁体   中英

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();
   }
}

From the javadoc

This method may block while waiting for input to scan

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM