Java 扫描仪无限循环导致浏览器挂起
我真的已经试着解决这个问题大约一个小时了,但我根本找不到解决办法 请看下面的代码:Java 扫描仪无限循环导致浏览器挂起,java,http,loops,browser,Java,Http,Loops,Browser,我真的已经试着解决这个问题大约一个小时了,但我根本找不到解决办法 请看下面的代码: 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(); } 如果我将浏览器(Chrom
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)连接到localhost,它将永远挂起。我必须按escape(强制它停止请求)来实际接收从它的请求派生的所有输入行
这个想法很简单;如果请求有下一行,只需使用该行直到没有剩余内容,然后发送200 OK响应。但这根本不起作用
编辑:
@Zutty询问了in的位置:
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();
}
}
}
}
如果使用HTTP,则应始终发送内容长度标头。然后,接收端确切地知道要读取多少字节的内容。这避免了所有混乱的“读取到EOF”或“直到我找到\r\n\r\n”问题。在中有什么
,它设置在哪里?要更快地获得更好的帮助,请发布一个。这段代码是在小程序中运行的吗?我认为它永远不会退出,因为它永远不会找到和EOF
。您应该搜索\r\n\r\n
以了解请求的结束位置。@DavideBerra我试图在nextLine.equals(“\r\n\r\n”)时中断while循环;但这似乎不起作用。我想这是因为第一次断线\r\n。您应该使用另一种方法解析内容