作为一个大型项目的一部分,我不得不制作一个自定义的Java线程池服务器。
我遇到了一个问题,这个问题让我头脑中的神经受到了至少一整天和一整夜的折磨。
我的做法很简单(遵循了一个在线资源)。我有一个无限循环的while循环。当有请求时,它接受并将其发送到线程池(Java执行器框架)。
protected ExecutorService threadPool = Executors.newFixedThreadPool(10);
while(! isStopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
if(isStopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException("Error accepting client connection", e);
}
this.threadPool.execute(
new Task(clientSocket,
"Test")
);
//System.out.println("Processed");
}
this.threadPool.shutdown();
这还能更简单吗?
而且Task类只接受一个socket,并写入它的输出流。
public class Task implements Runnable{
protected Socket clientSocket = null;
protected String serverText = null;
public Task(Socket clientSocket, String serverText) {
this.clientSocket = clientSocket;
this.serverText = serverText;
}
public void run() {
try {
InputStream input = clientSocket.getInputStream();
OutputStream output = clientSocket.getOutputStream();
long time = System.currentTimeMillis();
output.write(("HTTP/1.1 200 OK\n\nWorkerRunnable: " +
this.serverText + " - " +
time +
"").getBytes());
output.close();
input.close();
System.out.println("Request processed: " + time);
} catch (IOException e) {
//report exception somewhere.
e.printStackTrace();
}
}
}
问题背景:
在Chrome浏览器中输入localhost:9004时,尽管只点击一次URL,但控制台会显示(已处理请求:时间)多次。
问题原因:
可能存在某些原因导致向服务器发起多次请求,或者Java Executor框架的问题,例如执行了多次请求。但以上两种情况均不太可能。
Firefox表现:
当从Firefox浏览器打开该URL时,每次访问服务器时正确地显示了一个“Request Processed”。
自定义Java客户端表现:
从自定义Java客户端应用程序中打开URL时,服务器应用程序的控制台窗口会为每个请求正确地显示一个“Request Processed”标记。
IE表现:
与Chrome相同。请提供有关此情况的见解。对于问题长度我表示歉意。