When one clicks on an URL
link in a browser page, a request is sent to the computer at the
domain indicated. If no port is included, the default port 80
is used. The Web server is watching
this port and when a request arrives it will open a socket
for this client and provide the Web page or other service requested.
Other types of servers use other ports to provide services such
as database access, email, etc. Also, as mentioned earlier,
servers can be created with RMI,
thus directly calling methods in the server program itself. Here,
though, we will concentrate on socket type servers, such as web
Web serving is a stateless interaction, meaning that it
breaks off the connection after answering the request and does
not maintain any further connection information about that client.
Each interaction will require a new connection. (An on line store
might use a cookie file on the browser platform and the IP address
of the requestor to maintain information about an interaction
for a given period of time.)
Note that servers for other types of protocols, such as FTP,
can maintain a connection as long as necessary.
The Java Standard
Edition offers lots of resources to create and run your own
server such as a HTTP (web) server. The Enterprise Edition offers
many advanced tools and features but the J2SE provides sufficient
resources to build useful servers.
We will create a micro HTTP server that illustrates all
the basic components of a web server. Such a server could run
in an embedded processor and
provide information on, say, a sensor or display data from a scientific
instrument. See the references for similar server projects.
Note that since you customize the server as you wish, you don't
have to break off the connection (that is, close the socket) immediately
as with standard Web servers. We discuss in Chapter
15 a client/server system using sockets that can maintain
a continual connection.
Our little web server needs to
- Create a ServerSocket
instance that watches for incoming client requests.
- Create a Socket
to connect with a client.
- Spin off a thread to handle
the client's request
- Use stream I/O to receive
the clients' requests and to send responses.
The following pages will discuss each of these functions.