Untitled

 avatar
unknown
plain_text
5 months ago
2.0 kB
6
Indexable
import java.io.*;
import java.net.*;
import java.util.concurrent.*;

public class SimpleHttpServer {

    private static final int PORT = 8080;
    private static final int THREAD_POOL_SIZE = 5;
    private static ExecutorService executorService;

    public static void main(String[] args) {
        // Initialize the executor service with 5 threads
        executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {
            System.out.println("Server is listening on port " + PORT);

            while (true) {
                // Accept a new client connection
                Socket clientSocket = serverSocket.accept();

                // Handle the request using a separate thread
                executorService.submit(() -> handleRequest(clientSocket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleRequest(Socket clientSocket) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true)) {

            // Read the HTTP request (simple GET request in this example)
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.isEmpty()) {
                    break;  // End of request headers
                }
                System.out.println(line);  // Log the request for debugging
            }

            // Send a basic HTTP response
            String response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello, World!";
            writer.write(response);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
Editor is loading...
Leave a Comment