Java:实现多线程web服务器
努力练习。有两个问题困扰着我Java:实现多线程web服务器,java,multithreading,Java,Multithreading,努力练习。有两个问题困扰着我 在控制台上打印请求后,我应该在哪里停止线程?稍后,我需要在发送响应后执行此操作 我应该从哪里发回回复?我可以通过processRequest()轻松完成这项工作。我在想是否有必要发回HttpResponse。 从HttpRequest类本身发送响应可以吗 代码 主类 public final class WebServer { public static void main(String[] args) throws Exception {
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();
}
}
out.writeBytes()代码>
FileInputStream fileToClient;
OutputStream toClient;
byte[] buffer = new byte[2048];
int bytes = 0;
while ((bytes = fileToClient.read(buffer)) != -1){
toClient.write(buffer, 0, bytes);
}