嘗試在this assignment上練習。有兩個問題陷入困境。Java:實現多線程Web服務器
- 在控制檯上打印請求後,我應該在哪裏停止線程?稍後,我需要在發送回覆後這樣做。
- 從哪裏發回應答?我可以從
processRequest()
輕鬆完成。正在考慮是否無論如何發回HttpResponse。 從HttpRequest類本身發回響應可以嗎?
代碼
主要類
public final class WebServer {
public static void main(String[] args) throws Exception {
int port = 1983;
final ServerSocket server = new ServerSocket(port);
System.out.println("Comes here");
Socket client = null;
while (true) {
client = server.accept();
System.out.println("Got the connection" + client.toString());
final HttpRequest request = new HttpRequest(client);
Thread thread = new Thread(request);
thread.start();
}
}
}
HttpRequest.java
final class HttpRequest implements Runnable {
Socket socket;
public HttpRequest(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
processRequest();
} catch (IOException e) {
e.printStackTrace();
}
}
private void processRequest() throws IOException {
String headerline = null;
DataOutputStream out = null;
BufferedReader in = null;
out = new DataOutputStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((headerline = in.readLine()).length() != 0) {
System.out.println(headerline);
}
out.close();
in.close();
socket.close();
}
}