1

我期待收到 HTTP 响应,然后Socket关闭它,但它只是坐在那里,在页面返回后永远不会结束。我假设它与Scanner; 为什么这个程序永远不会结束?

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

2 回答 2

4

来自javadoc

此方法可能会在等待输入扫描时阻塞

于 2013-09-17T12:53:36.053 回答
2

它是一个流,因此 Java 无法预测输入何时何地结束。您需要指定一些“结束标记”,找到它并停止阅读。

while (sc.hasNextLine()) {
      String str = sc.nextLine();
      System.out.println(str);
      if(str.endsWith("</HTML>")) break;
}
于 2013-09-17T12:56:44.103 回答