我有一個非常基本的多線程Web服務器的啓動,它可以接收所有的GET請求,只要它們一次只有一個。Java多線程Web服務器 - 沒有收到多個GET請求
但是,當多個GET請求同時進入時,有時它們都會被接收,而其他時間會有一些丟失。
我通過創建一個帶有多個圖像標籤指向我的web服務器並在Firefox中打開頁面的html頁面來測試此項。我總是使用shift +刷新。
這是我的代碼,我必須做一些根本性的錯誤。
public final class WebServer
{
public static void main(String argv[]) throws Exception
{
int port = 6789;
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(port);
}
catch(IOException e)
{
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
while(true)
{
try
{
Socket clientSocket = serverSocket.accept();
new Thread(new ServerThread(clientSocket)).start();
}
catch(IOException e)
{
}
}
}
}
public class ServerThread implements Runnable
{
static Socket clientSocket = null;
public ServerThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
public void run()
{
String headerline = null;
DataOutputStream out = null;
BufferedReader in = null;
int i;
try
{
out = new DataOutputStream(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while((headerline = in.readLine()).length() != 0)
{
System.out.println(headerline);
}
}
catch(Exception e)
{
}
}
你可以從注意你的例外開始,而不是忽略它們。他們在那裏是有原因的;聽他們,你的答案可能在那裏。 – skaffman 2011-02-05 22:35:39