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

问题描述 投票:0回答:1

我在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();
                }
            });
        }
    }

我做错了什么?

java http java.util.concurrent
1个回答
0
投票

使用这段代码,希望对你有所帮助。

后发制人

 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);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.