我在vanilla Java上实现了HTTP服务器,并尝试使用ExecutorService。我尝试使用ExecutorService.第一次请求在浏览器中成功,但第二次请求却有无尽的加载。
我的代码 start()
服务器的方法。
public void start() throws IOException {
this.server = new ServerSocket(this.port);
ExecutorService executor = Executors.newCachedThreadPool();
client = this.server.accept();
while (true) {
executor.submit(() -> {
Socket cs = client;
try (PrintWriter out = new PrintWriter(cs.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(cs.getInputStream()))
) {
// write server http headers response
out.print("HTTP/1.1 200 OK \n");
out.print("Content-Type: text/plain\n");
out.print("Accept-Language: en-US, en; q=0.5\n");
// out.print("Connection: close\n");
out.print("\n");
String data;
// read client request
while ((data = in.readLine()) != null) {
if (data.length() == 0) {
out.write("EOF(End of file)");
break;
}
// write back to client its request as response body.
out.write(data + "\n");
}
out.close();
in.close();
cs.close();
} catch (IOException e) {
e.getMessage();
}
});
}
}
我做错了什么?
使用这段代码,希望对你有所帮助。
后发制人
BufferedReader objReader = null;
try {
String strCurrentLine;
objReader = new BufferedReader(new FileReader("D:\\DukesDiary.txt"));
while ((strCurrentLine = objReader.readLine()) != null) {
System.out.println(strCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objReader != null)
objReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
更新
PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8"),true);