A Simple Web Server
Example 5-8
shows a very simple web server, HttpMirror
. Instead of returning a requested
file, however, this server simply “mirrors” the request back to the
client as its reply. This can be useful when debugging web clients and
can be interesting if you are just curious about the details of HTTP
client requests. To run the program, specify the port that it should
listen on as an argument. For example, I can run the server like
this:
oxymoron% java je3.net.HttpMirror 4444
Then, in my web browser, I can load http://localhost:4444/testing.html. The server ignores the request for the file testing.html, but it echoes back the request that my web browser sent. It might look something like this:
GET /testing.html HTTP/1.1 Host: localhost:4444 User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.3) Gecko/20030312 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate,compress;q=0.9 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive
The main new feature introduced in Example 5-8 is the ServerSocket
class. This class is used by a
server, or any other program, that wants to sit and wait for a
connection request from a client. When you create a ServerSocket
, you specify the port to listen
on. To connect to a client, call the accept(
)
method of the ServerSocket
. This method blocks until a
client attempts to connect to the port that the ServerSocket
is listening on. When such a
connection attempt occurs, the ServerSocket ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.