O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required