我期待收到 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();
}
}
最佳答案
来自javadoc
This method may block while waiting for input to scan
关于java - 为什么这个程序不结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18850383/