At a basic level, network-based systems consist of
a server , client , and a media for communication
A computer running a program that makes a
request for services is called client machine.
A computer running a program that offers
requested services from one or more clients is
called server machine.
The media for communication can be wired or
Generally, programs running on client machines
make requests to a program running on a server
machine. They involve networking services
provided by the transport layer, which is part of
the Internet software stack, often called TCP/IP
(Transport Control Protocol/Internet Protocol)
The transport layer comprises two types of
(Transport Control Protocol)
UDP (User Datagram Protocol).
The most widely used programming
interfaces for these protocols are
TCP is a connection-oriented protocol that
provides a reliable flow of data between two
computers. Example applications that use such
services are HTTP, FTP, and Telnet.
UDP is a protocol that sends independent packets
of data, called “datagrams”, from one computer to
another with no guarantees about arrival and
sequencing. Example applications that use such
services include Clock server and Ping.
The TCP and UDP protocols use “ports” to map
incoming data to a particular process running on a
Port is represented by a positive (16-bit) integer
Some ports have been reserved to support
common/well known services like ftp, http, https
User-level process/services generally use port
number value >= 1024.
Every computer on the Internet is identified by a
unique, 4-byte IP address .
This is typically written in dotted quad format
like 220.127.116.11 where each byte is an
unsigned value between 0 and 255.
This representation is not user-friendly because it
does not tell us anything about the content and
then it is difficult to remember. Hence, IP
addresses are mapped to names like
www.google.com, which are easier to remember.
Domain name servers(DNS) translate these
names to IP addresses.
Computers often need to communicate and
provide more than one type of service or to talk to
multiple hosts/computers at a time. For example,
there may be multiple ftp sessions, web
connections, and chat programs all running at the
To distinguish these services, a concept of “port” s,
a logical access point, represented by a 16-bit
integer number is used.
That means, each service offered by a computer is
uniquely identified by a port number.
Each Internet packet contains both the
destination host address and the port number on
that host to which the message/request has to be
The host computer dispatches the packets it
receives to programs by looking at the port
numbers specified within the packets.
Sockets provide an interface for programming
networks at the transport layer.
A server runs on a specific computer and has a
socket that is bound to a specific port.
The server listens to the socket for a client to
make a connection request
If everything goes well, the server accepts the
Upon acceptance, the server gets a new socket
bound to a different port. It needs a new socket
(consequently a different port number) so that it
can continue to listen to the original socket for
connection requests while serving the connected
Socket is bound to a port number so that the TCP
layer can identify the application that data is
destined to be sent.
Java provides a set of classes, defined in a
package called java.net, to enable the rapid
development of network applications.
The two key classes from the java.net package
used in creation of server and client programs
SOCKET PROGRAMMING USING TCP
A server program creates a specific type of socket
that is used to listen for client requests (server
socket), In the case of a connection request, the
program creates a new socket through which it
will exchange data with the client using input
and output streams.
STEPS TO CREATE SERVER
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new
DataOutputStream os = new
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(“Hellon”);
5. Close socket:
STEPS TO CREATE CLIENT
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the
is = new DataInputStream(client.getInputStream());
os = new
3. Perform I/O or communication with the server:
Receive data from the server:
String line = is.readLine();
Send data to the server: os.writeBytes(“Hellon”);
4. Close the socket when done:
To send e-mail, you make a socket connection to port 25, the
SMTP port. SMTP is the Simple Mail Transport Protocol that
describes the format for e-mail messages.
1. Open a socket to your host.
Socket s = new Socket("mail.yourserver.com", 25); // 25 is
PrintWriter out = new PrintWriter(s.getOutputStream());
2. Send the following information to the print stream:
HELO sending host
MAIL FROM: <sender email address>
RCPT TO: <recipient email address>
(any number of lines)
Most SMTP servers do not check the veracity of the
information—you may be able to supply any sender you
Usually, you don't have to worry too much about Internet
addresses—the numerical host addresses that consist of
four bytes such as 18.104.22.168. However, you can use the
InetAddress class if you need to convert between host
names and Internet addresses.
The static getByName method returns an InetAddress
object of a host.
InetAddress address= InetAddress.getByName(“india.gov");
returns an InetAddress object that encapsulates the
sequence of four bytes 22.214.171.124.
You can access the bytes with the getAddress method.
byte addressBytes = address.getAddress();
Some host names with a lot of traffic correspond to
multiple Internet addresses, to facilitate load balancing.
For example, at the time of this writing, the host name
google.com corresponds to different Internet addresses.
One of them is picked at random when the host is
accessed. You can get all hosts with the getAllByName
InetAddress addresses =InetAddress.getAllByName(host);
Finally, you sometimes need the address of the local host.
If you simply ask for the address of localhost, you always
get the address 127.0.0.1, which isn't very useful. Instead,
use the static getLocalHost method to get the address of
your local host.
InetAddress address= InetAddress.getLocalHost();
The URL and URLConnection classes encapsulate much of the
complexity of retrieving information from a remote site.
URL url = new URL(urlString);
The Java 2 platform supports both HTTP and FTP resources.
If you simply want to fetch the contents of the resource, then you can
use the openStream method of the URL class. This method yields an
InputStream object. Using this stream object, you can easily read the
contents of the resource.
InputStream uin = url.openStream();
BufferedReader in =
new BufferedReader(new InputStreamReader(uin));
while ((line = in.readLine()) != null)
Posting Form Data
we saw how to read data from a web server. Now
we learn how your programs can send data back
to a web server and to programs that the web
server invokes, using the CGI (Common Gateway
check boxes and radio buttons are sent back to
the server to be processed by a CGI script.
The CGI script to use is specified in the ACTION
attribute of the FORM tag.
The CGI script is a program that resides on the
server computer. The web server launches the
CGI script and feeds it the form data.
What Is a Servlet?
Servlets are small programs that execute on the server side of a web
Just as applets dynamically extend the functionality of a web
browser, servlets dynamically extend the functionality of a web
In the early days of the Web, a server could dynamically construct a
page by creating a separate process to handle each client request.
It communicated with the web server via an interface Common
Gateway Interface (CGI). CGI allowed the separate process to read
data from the HTTP request and write data to the HTTP response.
CGI suffered serious performance problems.
It was expensive in terms of processor and memory resources to
create a separate process for each client request.
It was also expensive to open and close database connections for each
The CGI programs were not platform-independent
Advantages of Servlets
Servlets offer several advantages in comparison with CGI.
Performance is significantly better.
Servlets execute within the address space of a web server.
It is not necessary to create a separate process to handle
each client request.
servlets are platform-independent because they are written
the Java security manager on the server enforces a set of
restrictions to protect the resources on a server machine.
Finally, the full functionality of the Java class libraries is
available to a servlet. It can communicate with applets,
databases, or other software via the sockets that you have
The Life Cycle of a Servlet
init( ), service( ), and destroy( ) methods
HTTP request for generated for a URL.
Web server maps this request to a particular servlet which
is dynamically retrieved and loaded.
The server invokes the init( ) method of the servlet.
The server invokes the service( ) method of the servlet;
may also formulate an HTTP response for the client.
The server may decide to unload the servlet from its
memory using destroy() method
To create servlets, you will need access to a servlet
The one we will use is Tomcat. Tomcat is an opensource product maintained by the Jakarta Project of the
Apache Software Foundation. It contains the class
libraries, documentation, and runtime support that you
will need to create and test servlets.
Servlet- Declares life cycle methods for a servlet.
ServletConfig- Allows servlets to get initialization parameters.
ServletContext- Enables servlets to log events and access information
about their environment.
ServletRequest- Used to read data from a client request.
ServletResponse- Used to write data to a client response.
SingleThreadModel- Indicates that the servlet is thread safe.
Servlet API Contd…
GenericServlet- Implements the Servlet and ServletConfig
ServletInputStream- Provides an input stream for reading
requests from a client.
ServletOutputStream- Provides an output stream for
writing responses to a client.
ServletException- Indicates a servlet error occurred.
UnavailableException- Indicates a servlet is unavailable.
Servlet API Contd…
HttpServletRequest Enables servlets to read data from an
HttpServletResponse Enables servlets to write data to an
HttpSession Allows session data to be read and written.
Servlet API Contd…
Cookie- Allows state information to be stored on a client
HttpServlet- Provides methods to handle HTTP requests
HttpSessionEvent- Encapsulates a session-changed event.