这是有问题的程序的一部分。
public void run() {
while(!isStopped) {
try {
socket = server.accept();
System.out.println(socket.getRemoteSocketAddress() + " has connected");
//problem starts
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String request;
while((request = in.readLine()) != null) {
System.out.println(request);
} //problem ends
FileReader f = new FileReader("html/index.html");
BufferedReader br = new BufferedReader(f);
String response;
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out.write("HTTP/1.1 200 OK\r\n");
out.write("Content-type: text/html\r\n");
out.write("\r\n");
while((response = br.readLine()) != null) {
out.write(response);
}
out.close();
socket.close();
} catch(Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
我创建了一个java Web服务器,它适用于所有连接。但是当程序侦听来自客户端的请求并在控制台上打印该请求时,程序不会继续,因此它不会响应HTML文件。我试图摆脱打印请求部分和程序轻松发送HTML但我不喜欢它,因为它不打印初始请求。如何使服务器正确地监听和打印客户端请求并相应地发回响应并继续这样循环?展示代码会很棒。