Class HttpServer
When constructed, the HTTP server starts a thread listening for connections
to a given host and port. When a web browser sets up a connection, the HTTP
server calls the process()
method to process the request. This is an
abstract method that must be overridden in a subclass. The process()
method's arguments are an HttpRequest object from which the
method reads the HTTP request message and an HttpResponse object
to which the method writes the HTTP response message.
The HTTP server assumes that the process()
method will not perform
any lengthy processing and will not block the calling thread. If the HTTP
request requires lengthy processing or requires blocking, the
process()
method should spawn a separate thread to process the
request. A thread pool may prove useful; see package java.util.concurrent.
When a client opens a socket connection to the HTTP server, the server places
a two-second timeout on reading the socket. If the client does not send an
HTTP request message before the timeout, the HttpRequest's
isValid()
method returns false.
- Version:
- 29-Jul-2010
- Author:
- Alan Kaminsky
-
Constructor Summary
ConstructorDescriptionHttpServer
(InetSocketAddress address) Construct a new HTTP server.HttpServer
(InetSocketAddress address, Logger logger) Construct a new HTTP server. -
Method Summary
Modifier and TypeMethodDescriptionvoid
close()
Close this HTTP server.Obtain the host and port to which this HTTP server is listening for connections.protected abstract void
process
(HttpRequest theRequest, HttpResponse theResponse) Process the given HTTP request.
-
Constructor Details
-
HttpServer
Construct a new HTTP server. The HTTP server will print error messages on the standard error.- Parameters:
address
- Host and port to which the HTTP server will listen for connections.- Throws:
IOException
- Thrown if an I/O error occurred.IOException
- if any.
-
HttpServer
Construct a new HTTP server. The HTTP server will print error messages using the given logger.- Parameters:
address
- Host and port to which the HTTP server will listen for connections.logger
- Error message logger. If null, the HTTP server will print error messages on the standard error.- Throws:
IOException
- Thrown if an I/O error occurred.IOException
- if any.
-
-
Method Details
-
getAddress
Obtain the host and port to which this HTTP server is listening for connections.- Returns:
- Host and port.
-
close
Close this HTTP server.- Throws:
IOException
- Thrown if an I/O error occurred.IOException
- if any.
-
process
protected abstract void process(HttpRequest theRequest, HttpResponse theResponse) throws IOException Process the given HTTP request. Theprocess()
method must be overridden in a subclass to read the HTTP request fromtheRequest
and write the HTTP response totheResponse
.- Parameters:
theRequest
- HTTP request.theResponse
- HTTP response.- Throws:
IOException
- Thrown if an I/O error occurred.IOException
- if any.
-