我正在尝试构建简单的Java Web服务器。来自客户端的每个请求都必须由单独的线程支持。我写了这样的话:
this.serverSocket = new ServerSocket(this.serverPort);
while (!this.isStopped) {
Socket clientSocket = null;
clientSocket = this.serverSocket.accept();
HttpClient client = new HttpClient(clientSocket);
new Thread(client).start();
}
HttpClient类的run()函数:
public void run()
{
try {
InputStream input = client.getInputStream();
OutputStream output = client.getOutputStream();
Thread.sleep(1000);
output.write("HTTP/1.1 200 OK".getBytes());
output.write(("\n\nWorkerRunnable: dd").getBytes());
output.close();
input.close();
} catch (IOException ex) {
Logger.getLogger(HttpClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(HttpClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
当我扔掉时
Thread.sleep(1000);
一切正常,但有了这个浏览器无法与服务器连接。
有什么问题?
答案 0 :(得分:1)
尝试在Thread.sleep(1000);
语句后添加output.write(...)
。您应该尽快确认客户端,然后等待。