Class SSEHandler

java.lang.Object
com.ns.tcpframework.reqeustHandlers.RequestHandler
com.ns.tcpframework.reqeustHandlers.sse.SSEHandler

public class SSEHandler extends RequestHandler
Handler for Server-Sent Events (SSE) connections.

This class manages SSE connections between the server and multiple clients, enabling real-time, one-way communication from server to clients. It maintains a pool of active socket connections and broadcasts events such as logs, statistics, heartbeats, and connection status updates to all connected clients.

The handler supports the following event types:

Thread-safety: This class uses a ConcurrentHashMap-backed set to safely manage socket connections across multiple threads.

See Also:
  • Constructor Details

    • SSEHandler

      public SSEHandler()
  • Method Details

    • handle

      public HTTPResponse handle(HTTPRequest request) throws IOException
      Not supported - SSE requires socket access.

      This method is inherited from RequestHandler but cannot be used for SSE connections because they require direct socket access for streaming. Always throws an IOException directing users to use handle(HTTPRequest, Socket) instead.

      Specified by:
      handle in class RequestHandler
      Parameters:
      request - The HTTP request (ignored).
      Returns:
      Never returns normally.
      Throws:
      IOException - Always thrown with message indicating socket is required.
    • handle

      public HTTPResponse handle(HTTPRequest request, Socket socket) throws Exception
      Handles an SSE connection request by establishing a persistent event stream.

      This method:

      1. Sends appropriate SSE headers (Content-Type, Cache-Control, etc.)
      2. Registers the client socket in the active connections pool
      3. Broadcasts a CONNECTED event to all clients with updated connection count
      4. Enters a keep-alive loop that periodically sends:
        • HEARTBEAT events (every 1 second)
        • STATS events with server metrics (every 1 second)
      5. Cleans up the connection when the socket closes

      This method blocks until the socket is closed or an error occurs. It should be run on a dedicated thread per client connection.

      Overrides:
      handle in class RequestHandler
      Parameters:
      request - The HTTP request that initiated the SSE connection.
      socket - The client socket for the SSE stream.
      Returns:
      The HTTP response with SSE headers (sent immediately).
      Throws:
      Exception - if an error occurs during connection setup or maintenance.
    • broadcast

      public void broadcast(SSEEvent event, String message)
      Broadcasts an SSE event to all connected clients.

      This method formats the event according to the SSE protocol specification:

      event: {eventName}
      data: {message}
      
      
      The formatted message is then sent to every active client socket. If sending to any client fails, that client is automatically disconnected and removed from the active connections pool.

      Thread-safety: This method is thread-safe and can be called concurrently from multiple threads.

      Parameters:
      event - The type of SSE event to broadcast (e.g., LOG, STATS, HEARTBEAT).
      message - The message payload to send with the event.
      See Also:
    • send

      public void send(Socket socket, String message)
      Sends a message to a specific client socket.

      This method attempts to write the message to the socket's output stream and flush it. If an IOException occurs (e.g., client disconnected), the socket is automatically closed and removed from the active connections pool.

      Parameters:
      socket - The client socket to send the message to.
      message - The message string to send.
    • hasClients

      public boolean hasClients()
      Checks if there are any active SSE client connections.

      This is a convenience method for determining whether any clients are currently connected to the SSE stream.

      Returns:
      true if at least one client is connected, false otherwise.
    • clientCount

      public int clientCount()
      Returns the current number of active SSE client connections.

      This method provides a snapshot of the connection count at the time of invocation. The count may change immediately after the method returns due to concurrent connections or disconnections.

      Returns:
      The number of currently connected clients.