Java Reference
In-Depth Information
distributed in a scientific experiment, on a factory assembly line, or in power
plant equipment.
14.2 Designing a web server
When you click on a URL link in a browser page, a request is sent to the computer
at the host address given in the URL. If the port is not specified, the request goes
to the default port 80. The web server program monitors this port and, when a
request arrives, the server opens a socket for the client and sends the web page
or other data requested.
Different types of servers monitor different ports to provide services such as
database access, email, audio/video streaming, and so forth. Web serving is a
stateless interaction in that the connection ends after answering the request and
the server does not usually maintain any further information about the client. If
the same client returns later, then a completely new session is created with no
knowledge about the previous session. (An online 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.) There is no continuous connection
as in a telnet session, for example.
With Java you can create and run your own web server that follows the HTTP
protocols. On Unix machines, the ports numbered 0-1023 are restricted but other-
wise your server is free to choose whatever port it wants to monitor for clients
requesting a connection.
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.
In this chapter we develop MicroServer ,abasic HTTP server that illus-
trates all the basic components of a web server. (It is similar to an example in the
book by Niemeyer and Knudsen [3].) To serve its clients, our little web server
needs to:
create a ServerSocket instance that watches for incoming client requests
create a Socket instance to connect with a client
spin off a thread to handle the client's request
set up streams to carry out the I/O with the client
The following sections discuss each of these tasks.
14.2.1 ServerSocket
In Chapter 13 we briefly discussed communications with the Socket and
ServerSocket classes. In the code snippet below, the ServerSocket object
waits for a client to request a connection. The accept() method blocks (i.e.
doesn't return) until the client connects, and then it returns an instance of Socket .
Search WWH ::




Custom Search