gpt4 book ai didi

java - 如何使用 ExecutorService Java 在新线程上运行每个客户端?

转载 作者:行者123 更新时间:2023-12-01 16:42:18 28 4
gpt4 key购买 nike

我正在 vanilla Java 上实现 HTTP 服务器。我尝试使用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();
}
});
}
}

我做错了什么?

最佳答案

使用此代码希望对您有所帮助

catch之后使用finally来关闭

 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);

关于java - 如何使用 ExecutorService Java 在新线程上运行每个客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61839368/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com