0
我真的一直在努力解决这个问题约一个小时,但我根本无法找到它的解决方案。扫描器无限循环导致浏览器挂起
请看下面的代码:
public void handleRequest() throws IOException {
while(in.hasNextLine()) {
System.out.println(in.nextLine());
}
out.print("HTTP/1.0 200 OK\r\n\r\ntest");
out.flush();
}
如果我在我的浏览器(Chrome)连接到本地主机,它会挂到永远。我必须按下escape(强制它停止请求)才能实际接收从请求中获得的所有输入行。
这个想法很简单;如果请求有下一行,那么只需要截取该行,直到没有任何内容,然后发送200 OK响应。但这根本不起作用。
编辑:
@Zutty问其中位于:
public class HttpServer {
public static final int PORT = 80;
public static final int BACKLOG = 1;
public static final String ROOT_CATALOG = "C:/HttpServer/";
private ServerSocket server;
private Socket client;
private Scanner in;
private PrintWriter out;
private FileInputStream fstream;
private final String TWOHUNDRED = "HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "\r\n";
public HttpServer() throws IOException {
server = new ServerSocket(PORT, BACKLOG);
}
public Socket accept() throws IOException {
client = server.accept();
in = new Scanner(client.getInputStream());
out = new PrintWriter(client.getOutputStream());
return client;
}
而且在主:
public class Main {
public static void main(String[] args) throws IOException {
HttpServer server = new HttpServer();
while(true) {
try(Socket client = server.accept()) {
server.handleRequest();
}
}
}
}
什么是'在'和它在哪里设置? – Zutty 2013-03-07 16:23:38
为了尽快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。这个代码是在一个applet中运行的吗? – 2013-03-07 16:29:14
我认为它永远不会退出,因为它永远找不到和'EOF'。你应该搜索'\ r \ n \ r \ n'来知道请求结束的地方。 – 2013-03-07 16:36:56