java编程实现一个HTTP服务器程序和HTTP客户端程序,使用线程池处理客户端请求
时间: 2023-11-28 10:47:11 浏览: 100
用线程池解决服务器并发请求的方案设计
以下是一个简单的Java HTTP服务器程序和客户端程序实现,使用线程池来处理客户端请求:
HTTP服务器程序:
```java
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HTTPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8000);
ExecutorService pool = Executors.newCachedThreadPool();
while (true) {
Socket socket = serverSocket.accept();
pool.execute(new RequestHandler(socket));
}
}
}
class RequestHandler implements Runnable {
private final Socket socket;
public RequestHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
String request = in.readLine();
System.out.println("Request: " + request);
out.writeBytes("HTTP/1.1 200 OK\r\n\r\n");
out.writeBytes("Hello World!");
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
HTTP客户端程序:
```java
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class HTTPClient {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
ExecutorService pool = Executors.newCachedThreadPool();
while (true) {
System.out.print("Enter URL (or 'exit' to quit): ");
String input = scanner.nextLine();
if (input.equals("exit")) {
break;
}
URL url = new URL(input);
pool.execute(new RequestHandler(url));
}
scanner.close();
}
}
class RequestHandler implements Runnable {
private final URL url;
public RequestHandler(URL url) {
this.url = url;
}
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个示例中,服务器监听端口8000并使用线程池来处理客户端请求。每当一个客户端连接到服务器时,服务器会为其分配一个线程来处理请求。当客户端发送HTTP GET请求时,服务器将返回“Hello World!”消息。
客户端程序允许用户输入URL并使用线程池来发送HTTP GET请求。每个请求也会分配一个线程来处理响应。响应将被打印到控制台上。
阅读全文