请设计一个简单的Java服务,用多线程处理请求。
以下是一个简单的Java服务,使用多线程处理HTTP请求。这个示例服务接收GET请求,并返回一个随机的欢迎消息。
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadedHttpServer {
private static final int PORT = 8080;
private ExecutorService executorService;
public MultiThreadedHttpServer() {
executorService = Executors.newFixedThreadPool(10); // Adjust the number of threads according to your system resources
}
public void startServer() throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("HTTP server started on port " + PORT);
while (true) {
Socket clientSocket = serverSocket.accept();
executorService.execute(new RequestHandler(clientSocket)));
}
}
private class RequestHandler implements Runnable {
private Socket socket;
public RequestHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())))) {
String request = br.readLine(); // Read the HTTP request from client
// Handle the request and generate a response
int randomIndex = (int) Math.random() * 10; // Generate a random index between 0 and 9
String welcomeMessage = "Welcome to MultiThreaded HTTP Server! Random Index: " + randomIndex;
OutputStream os = socket.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"))); // Set the output encoding to UTF-8
bw.write("HTTP/1.1 200 OK\n"); // Send the HTTP response header
bw.write(welcomeMessage + "\n\n"); // Write the welcome message and ending line break
bw.flush(); // Ensure that the response is sent immediately
} catch (IOException e) {
System.err.println("Error handling request: " + e.getMessage());
} finally {
if (socket != null) { // Make sure to close the socket properly
socket.close();
}
}
}
}
public static void main(String[] args) throws IOException {
MultiThreadedHttpServer httpServer = new MultiThreadedHttpServer();
httpServer.startServer(); // Start serving HTTP requests
}
}
这个服务会监听8080端口,对于每一个HTTP GET请求,都会创建一个新的线程来处理这个请求。服务器会生成随机欢迎消息作为响应,并关闭连接。
还没有评论,来说两句吧...