我一直在尝试解决这个问题大约一个小时,但我根本找不到解决方案。
看下面的代码:
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();
}
}
}
}