Java Reference
In-Depth Information
Implementing your own lightweight HTTP server consists of three tasks:
1. Createtheserver.Theabstract
HttpServer
classprovidesan
HttpServer
create(InetSocketAddress addr, int backlog)
class method
for creating a server that handles the HTTP protocol. This method's
addr
ar-
gumentspecifiesa
java.net.InetSocketAddress
objectcontainingan
IPaddressandportnumberfortheserver'slisteningsocket.The
backlog
ar-
gumentspecifiesthemaximumnumberofTCPconnectionsthatcanbequeued
while waiting for acceptance by the server; a value less than or equal to zero
causesasystemdefaultvaluetobeused.Alternatively,youcanpass
null
to
addr
orinvoke
HttpServer
's
HttpServer create()
classmethodto
createaservernotboundtoanaddress/port.Ifyouchoosethisalternative,you
will need to invoke
HttpServer
's
void bind(InetSocketAddress
addr, int backlog)
method before you can use the server.
2. Create a context. After creating the server, you need to create at least one
context (an instance of a subclass of the abstract
HttpContext
class) that
maps a root URI path to an implementation of
HTTPHandler
. Contexts
help you organize the applications run by the server (via HTTP handlers).
(The
HttpServer
Java documentation shows how incoming request URIs
are mapped to
HttpContext
paths.) You create a context by invoking
Ht-
tpServer
's
HttpContext createContext(String path, Ht-