Java简单的web服务器多线程,代码实例
时间: 2024-10-15 20:13:04 浏览: 18
Java的简单Web服务器使用多线程可以更好地处理并发请求。这里是一个基于Socket编程的简单示例,使用了`java.net.ServerSocket`和`java.lang.Thread`:
```java
import java.io.*;
import java.net.*;
public class SimpleWebServer {
private ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
new SimpleWebServer().start();
}
public void start() throws IOException {
serverSocket = new ServerSocket(8080); // 设置监听端口
System.out.println("Server started on port " + serverSocket.getLocalPort());
while (true) { // 无限循环接收新连接
Socket clientSocket = serverSocket.accept(); // 接收客户端连接
Thread handlerThread = new ClientHandler(clientSocket);
handlerThread.start(); // 创建新线程处理请求
}
}
private class ClientHandler extends Thread {
private Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String requestLine = in.readLine();
if (requestLine.startsWith("GET")) {
handleGetRequest(requestLine, out);
} else {
out.println("HTTP/1.1 405 Method Not Allowed");
out.flush();
}
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleGetRequest(String requestLine, PrintWriter out) throws IOException {
// 这里仅做基本响应,实际应用需要解析路径并返回相应内容
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/plain");
out.println();
out.println("Hello from simple web server!");
out.flush();
}
}
}
```
这个例子创建了一个监听指定端口的服务器,当有新的TCP连接到来时,会创建一个新的线程去处理每个客户端的请求。
阅读全文