Class HTTPHandler

java.lang.Object
com.ns.tcpframework.HTTPHandler

public class HTTPHandler extends Object
Handles incoming HTTP connections and delegates request processing to appropriate handlers.

This class serves as the primary entry point for processing HTTP requests in the server. It manages the request lifecycle from initial socket connection through response delivery, including request parsing, routing, handler execution, and error handling.

Key responsibilities:

  • Accepting client socket connections and submitting them to a thread pool
  • Parsing raw HTTP requests from socket input streams
  • Resolving virtual hosts based on the Host header
  • Routing requests to appropriate RequestHandler implementations
  • Executing handlers and managing HTTP responses
  • Tracking server statistics (request counts, active connections)
  • Logging request activity and errors
  • Handling exceptions and generating error responses

Request processing flow:

  1. Client connects and socket is submitted to thread pool via handle(Socket, ExecutorService)
  2. HTTP request is parsed from socket input stream
  3. Virtual host is resolved based on Host header
  4. Router finds appropriate handler for the request path
  5. Handler processes request and generates response
  6. Response is sent to client (if not already sent by handler)
  7. Socket is closed and resources are cleaned up

Thread-safety: This class is thread-safe and designed for concurrent request handling. Each request is processed in its own thread from the provided ExecutorService.

See Also:
  • Constructor Details

    • HTTPHandler

      public HTTPHandler(VirtualHostManager vManager)
      Constructs an HTTPHandler with the specified virtual host manager.

      The virtual host manager is used to resolve which virtual host configuration should handle each incoming request based on the HTTP Host header.

      Parameters:
      vManager - The VirtualHostManager managing virtual hosts and their configurations. Must not be null.
  • Method Details

    • handle

      public final void handle(Socket socket, ExecutorService pool)
      Handles an incoming socket connection by submitting it to a thread pool for processing.

      This method immediately returns after submitting the connection handling task to the thread pool, allowing the server to accept new connections without blocking. The actual request processing occurs asynchronously in a worker thread.

      The method ensures proper resource cleanup by using try-with-resources to automatically close the socket after processing completes, regardless of whether processing succeeds or fails.

      Error handling: Any exceptions thrown during request processing are caught, logged via ServerLogger, and printed to standard error. The socket is closed automatically even if an error occurs.

      Parameters:
      socket - The client socket representing the incoming connection. Must not be null and should be open and connected.
      pool - The thread pool (ExecutorService) used to execute the handling task asynchronously. Must not be null and should be running.
    • runTask

      protected void runTask(Socket socket) throws Exception
      Processes the HTTP request and delegates it to the appropriate request handler.

      This method orchestrates the complete request processing pipeline:

      1. Parses the raw HTTP request from the socket input stream
      2. Increments the server statistics request counter
      3. Logs the request details (excluding certain paths like _next and HEAD requests)
      4. Resolves the virtual host configuration based on the Host header
      5. Uses the router to find the appropriate handler for the request path
      6. Invokes the handler to process the request and generate a response
      7. Sends the response to the client if not already sent by the handler

      Selective logging: To reduce noise in logs, certain requests are excluded from debug logging:

      • Requests containing "_next" in the path (Next.js internal resources)
      • HEAD method requests (metadata-only requests)
      • Requests to "/api/active-clients" (high-frequency polling endpoint)

      Error handling: Any exceptions thrown during request processing are caught and passed to HTTPErrorHandler.handleException(Socket, Exception), which generates and sends an appropriate HTTP error response to the client.

      Response handling: Some handlers (e.g., SSE handlers) may send responses directly to the socket. The HTTPResponse.isSended() flag is checked to avoid sending duplicate responses.

      Parameters:
      socket - The client socket representing the connection. Must not be null, should be open and connected.
      Throws:
      Exception - If an unrecoverable error occurs during request processing. Note that most exceptions are caught internally and converted to HTTP error responses.