You are on page 1of 8

Lesson 05: Simple Web Server Using Java

5.0 Introduction

Learning outcome:

Now that we have learned about the HTTP in some detail after completing this lesson you will
be able to write client/server applications in Java and to combine both knowledge and build a
simple web server.

In this lesson we will learn about the Transport layer protocols which deliver data
between applications and how to build client server applications using different
protocols. We will learn about how applications identify each other using IP addresses,
ports and how sockets are used to create connections between applications. We will
also learn how to use Java classes to build client server applications, where servers
provide services to the clients that request for such services. Finally, you will build a web
server, which is a special type of server that serves resources such as files, images or
even output from another process to a requesting client.

5.1 IP Addresses, Ports and Sockets

You are already aware that the individual computers on a network are uniquely
identified by an IP address. Generally, a computer is connected to a network through
a single Network Interface Card, commonly known as the Network Card. Each network
card is assigned an IP addresses that will allow other computers to identify and
communicate with it using this address. All data that are exchanged between an
application running on a computer and the outside travels via this interface. A
computer may at any given time run several applications that require communication
with external processes. In order to identify the data that is associated with each
application, the concept of a port is introduced. A port can be considered as a
gateway to an application. Each application is associated with a particular port, and
each port is given a unique number, as shown in the Figure.

P# Application

P# Application
IP Address

P# Application
An application that need to use the services of another application running on a
remote computer need to identify the service required by specifying the IP address
and the Port no. Some of the ports are well-known, for e.g. Web servers generally run
on Port 80, and hence there is no need to specify the port number explicitly when a
web client such as Firefox or Internet Explorer connects to a web server running on
the Port 80. However, if the web server is running on any other port, then the client
needs to specify the IP address as well as the port number.

When a process needs to connect to another process, the two processes establish a
two way communication link between themselves. Each end-point of this
communication link is called a socket. In essence, the two applications that need to
exchange the data create a pair of sockets that act as the end-points of the
communication link.

Application Application

Figure : Socket

As we see in Figure, a socket is an end point of a communication link between two

applications, for e.g. a client program and a server program. All communication
between two processes happen through sockets, while the identification of a
particular process is done with an IP address and a port number.

5.2 Socket Programming with TCP

TCP is a connection oriented reliable transport layer protocol. Two processes that
communicates using the TCP protocol creates a communication "pipe" prior to the
communication sessions. All data between the processes flow through this "pipe". We
can think of a socket as the end point of this pipe. The pipe remains in operation until
one of the processes using the pipe closes it. Each end-point of the pipe or the socket
has two associated streams, one for input and one for output.

In TCP based communication the order of the data is guaranteed, i.e. the data sent by
one application to another application is guaranteed to be delivered in the same order
in which it was sent. This protocol also guarantees that data is delivered error free.
TCP ensures that any lost packets or packets received in error are retransmitted and
no duplicate packets are received by the destination machine. It also ensures that the
rate of data transmitted between two machines take into considerations the rate at
which the receiver can receive the data and adjusts the flow control accordingly.

Now we will write a simple client-server application using the TCP protocol in Java.
We will write the code to implement a simple server and then write the code to
implement a simple client that uses the services of the server.

Java provides a set of classes packaged into the package to create
connections between clients are servers. The main classes that are of interest to us at
the moment are the following:

Socket Class: Creates a client side socket.

ServerSocket Class: Creates a server side socket.

Thus creating a client server application requires us to write a server that would
provide some service. For example, a web server will serve resources identified by
URLs. Some of the resources that may be served by a server include a static web page
or the results of a process run on the server. A time of day server may serve the time
of the local machine. A quote server may serve quotes to a client application that
request such a service. A server application uses an instance of a ServerSocket class
bound to a particular port of the machine. to continuously listen to the port to check
whether a client is requesting for a service.

A client connects to a ServerSocket by creating a socket at the client side with the host
name and the port number of the remote application as parameters. When a
ServerSocket receives a request, it will create a new socket for the communication
session with the client. Each communication link with a client that connects to the
Server will be through a new socket created by the ServerSocket object.

The following table summarises different steps of writing a server application and a
client application.

Server Application
Create a server socket bound to a Port
While server open
Accept a request and create a connection socket for the request
Get a handle to the output stream of the socket to send data to the client
Get a handle to the input stream of the socket to the receive data from the
Read the client data through the input stream
Process the user request
Send the results of processing the request back to the client through the output
Close the input stream
Close the output stream
Close the connection socket (not the server socket)
End while
close the server socket

Client Application
Establish a connection by creating a socket bound to the host name and the port
Get a handle to the output stream of the socket to send data to the server
Get a handle to the output stream of the socket to the receive data from the server
While data available
Send data to the server
Read data from the server
Process read data
End While
Close the input stream
Close the output stream
close the socket

Next we look at the implementation of a Simple server and a client program in java.

In this application, the server will receive a request for the temperature from a client,
and sends back the current temperature. For simplicity's sake, the temperature will be
hard coded in the server code. Since the server does not do anything other than
serving the temperature, the client can send any message to the server and the server
will respond back with the currently known temperature. Again, to keep the system as
simple as possible, each client request will be treated as a single request and the
connection will be terminated once the data is sent back to the client.

The source code implementing the above steps are given in the two files, and

5.3 Socket Programming with UDP

The other common transport layer protocol in use is the User Datagram Protocol
(UPD), which delivers messages as data packets known as datagrams. UDP does not
guarantee neither the delivery nor the sequence of messaging. Each datagram is an
independent data packet that contains the host and the port number of the
application that the data is sent to. This is different than TCP based communication.
For analogies sake, a TCP connection can be compared to a telephone conversation
where once a connection is established two parties can have a continuous
interchange of sequential data. On the same line of thinking, a UDP connection can be
compared to a series of messages sent through ordinary postal mail. Each message or
letter has to have the destination address and there is no guarantee that the
messages will be delivered in the same order that were sent. In addition, UDP does
not guarantee error free transmission of data. Thus, all data packets sent by a process
may not be received by the destination process.

Since the UDP is a datagram based protocol, there is not connection establishment
phase in UDP based communication between two clients. The sockets creates to send
and receive data by a process is also different from TCP based sockets. As each packet
of data travels independently of other packets, there are no streams associated with
the end points of the communication or sockets.

Java provides several classes that facilitates UDP based data communication, such as
the DatagramSocket and DatagramPacket classes.

DatagramSocket Class: Creates a datagram socket through which data is sent and

DatagramPacket Class: A datapacket that will contain the actual data to be sent, the
length of the data packet, the IP address of the receiving process and the port number
of the receiving process.

Writing a UDP based client program involves the following steps:

Create a datagram socket
Create the data packet to be sent
Send the data packet through the datagram socket
Receive any data sent by the server from the datagram socket.

Writing a UDP based server would include the following steps:

Create a serversocket using the DatagramSocket class
Create a datagram packet structure to receive the client data
Read the client data into the datagram packet created
Extract the data portion of the packet for processing and the IP address and the
port number to reply to the client
Create a new datagram packet to be sent to the client
Send the datagram packet to the client.

The source code implementing the above steps are given in the two files, and

5.4 Building a Simple Web Server

Now you are ready to implement a simple web server. A web server accepts HTTP
requests from a client, fetches the required URL (a static file or a process), and return
either the web page or the output from the process to the client. To keep this exercise
simple we will assume that the server will accept a single HTTP request from the
client, serves the Resource to the client. Also for the simplicities sake, we will assume
that only requests for static pages with .html or .htm extensions are serviced.

Writing the server:

The following steps are required to implement the web server
Create a ServerSocket to listen to client requests
Parse the client request
Identify the resource (web page) requested
Fetch the resource (web page) from the storage location (hard disk)
Send the HTTP header information and the actual file to the client
Close the server socket

In order to implement this simple server, you need to be aware of the basic HTTP
header information passed between the web client and web server:

Client side header information

To start a request the client sends a header line of the form
GET <filename> HTTP/1.0
<blank line>
Where the filename is the name of the file required.

The server needs to send the following HTTP header information to the client before
sending the actual data:
HTTP/1.0 200 File Found
<blank line>
Content-Type: <content type>
Content-length: <file size>
<actual data>
<content type> refers to the MIME type of the file such as "image/jpeg", "image/gif",
and "text/html"
Independent Work
Analyse the use of the two Transport Layer protocols, TCP and UDP by different
applications. Reason out why each protocol is most suited for the applications that you
have studied. Some example applications are, Electronic mail, Web server, Remote
terminal, Streaming multimedia, Internet telephony, Network management

Programming Exercise
Develop a simple web server that would accept requests for static files and serves them
to the client.
Performance Indicators:

Describe the use of sockets

Set up the example client/server Java program
Design a simple web server using Java