Networking With Java
Networking With Java
7 NETWORKING
To implement networking in Java, java.net package classes, that give access to IP address, and a
range of methods related to TCP, UDP, and URL. IO stream classes are also used to read and write
data from and to communication channel. A virtualstream is provided by TCP, which supports IP
connection across the network. The virtualstream supports IO stream to transport data from and to
either of the connection. There are two important classes that participate in communication.
InetAddress class provides IP address of target connection. Socket class using to creates TCP
connection. Once a connection has been created, we bind both the end socket with their streams,
and communication will start by writing and reading data on these streams to and from remote
application.
7.1 Basics of Networking
Networking means transmitting data from one device to another device on the network, but both
devices must use the same protocol for transmission. There is an array of stack, called protocol
stack that involves everything from giving the data to physical device by converting that in voltage
pulse to delivering data streams to applications for which it was destined to.
Fig 1 Stack of Layer
Each layer provides an abstraction and dedicated to a specific fix set of jobs. The intermediate
layers also work as an interface between its upward and downward layer, first and the last. The two
most famous and important network stacks are given below:
Fig 2 OSI Layer networking stack Fig 3 TCP/IP Layer networking stack
Each layer communicates only with its immediate above and below layers. Encapsulation and
decapsulation are two mechanism, that embed each layer’s packets into the immediately below
layer packet, and reverse the process as the data moves up at the receiving machine, respectively.
An internet is a bunch of networks of different types of environments. The internet is exclusively
the worldwide set of connections of TCP/IP networks which use IP address and protocols under
the ultimate command.
7.2 Sockets
A Socket represents a TCP connection with a machine on network. This class facilitate in
establishing the streambased channel with a remote machine. For TCP/IP communication, there is
a need to create a Socket with the remote machine. The class Socket class creates a socket and
automatically established a TCP connection, and throws an exception if it fails. Socket address is
the combination of two components: one is host id, which can refer to the host name, IP address,
and the port number. The port number is an integer value that lies between 1 and 65536. In fact, on
every host, there are 655636 different addresses. But there must be a server, and dynamically
listening on the specified port.
Fig 4 Socket
There are two constructor of the Socket class. Creating a Socket object automatically connects to
the given host and port. As earlier given, that a server actively listen the request, but as connection
is refused an IOException will be thrown, unknown hostname can be other possibility of
connection failure.
Socket(String hostName, int portNumber) throws IOException creates a Socket object and
connects to the given host on the given port number.
Socket sckt = new Socket(“mymac”, 1889);
Socket(InetAddress hostAddress, int portNumber) throws IOException creates a Socket object
and connect to the given host address on the given port number.
InetAddress mac = InetAddress.getByName(“127.0.0.1”);
Socket sckt = new Socket(mac.getAddress, 1889);
OR
Socket sckt = new Socket(“127.0.0.1”, 1889);
Socket class methods provide the identification of remote host, port number of remote and local
host; also give the stream for communication. First create the Socket object to perform
communications across a TCP connection. After creating the socket, bind it with the required or
corresponding stream with the help of getInputStream() and getOutputStream() methods to
communicate with the remote server. The client and server, both will have both an InputStream
and an OutputStream for the purposes of communication.
Methods of java.net.Socket class
InputStream getInputStream() Method returns an InputStream that allow streambased
throws IOException communications for TCP connections. The data written by a host at
one end; can be read by remote host from this InputStream at other
end of the connection. The method actually returns a
SocketInputStream. The SocketInputStream is a nonpublic class.
InetAddress getInetAddress() Method returns the IP address of the remote host.
int getPort() Method returns the port number of the remote host to which the
Socket is connected.
Int Method returns the local port number, i.e., the port number of the
getLocalPort() Socket itself. Every TCP connection in fact consists of IP address
and port number of local machine; and IP address and port
number of remote machine, which will generally be different. A
random and unused port number is assigned to Socket at its
creation time.
7.3 Internet Addressing
TCP/IP is the architecture, implemented on the internet. The foundation of the TCP/IP is the IP
(internetworking protocol). IP works on 3rd layer of the architecture, i.e. network layer. The
application of IP is addressing hosts and routing data packets (also called datagram) between them.
There are two versions of IP, IPv4 and IPv6. IPv4 contains 32bit long address, while IPv6
contains 128bit long address.
In the chapter we will use IPv4 addressing. IPv4 format is xx.xx.xx.xx, where each two
consecutive ‘x’ (xx) separated by dot (.) are one byte, such as 168.196.12.1. Every IP address
belongs to any network. Network falls into five different classes. The class can be used to
determine the number of host in the network of which it is a member.
Class A : 1 – 126 (16M hosts)
Class B : 128 – 191 ( 65536 hosts each)
Class C : 192 223 (256 hosts each)
Class D : 224 – 239 (addresses for multicasting)
Class E : 240 – 255 (addresses reserved for future use)
The class defines the network size of the organization.
An IP datagram contains a header and a protocol data unit (PDU). The header collections of
information about fragmentation, length, time to live (TTL), and similar parameters. The PDU
contains the encapsulated data, which generally means a TCP segment or UDP packet.
Transmission Control Protocol (TCP) is a connectionoriented protocol that is on top of IP. TCP
packets, called segments, are encapsulated with IP datagram. Encoding of TCP occurs at the end
point of communication channel, i.e. at hosts. Routers inspect the IP packets to route TCP
encoding and decoding occur at the hosts which form routing decisions.
TCP provides guaranteed data transmission at the destination host’s application because of its
connectionoriented features. TCP is not responsible for exact arrival time, or transfer rate at which
data will be sent to remote end, only gives surety about delivery of uncorrupted and in order data.
User Datagram Protocol (UDP) is a connectionless transport layer protocol that is on top of IP. It
doesn’t provide state management and data integrity functions. It also not provides any congestion
avoidance, and packet delivery guarantee facility. If any received packed is corrupted it simply
throws it away.
7.4 Network Classes and Interface
For networking, java uses java.net package. The classes contained in the java.net package are
listed below:
The java.net package’s interfaces are listed here:
7.5 Inet Address
Computer on internet is identified by IP address, that is currently in two version with different size,
in IPv4, it is 32bit long (four byte) and in IPv6, it is 128bit long (eight byte). InetAddress
provides an abstraction to access IP address that is shown in the figure given below.
Fig 5 Abstraction provided by InetAddress
There is no constructor of this class. The class provides some static methods to create the instance
of the class, i.e. an object.
Methods of java.net.InetAddress class
static InetAddress getLocalHost() throws Method returns an object corresponding to
UnknownHostException the local machine.
static InetAddress getByName(String Method returns an object of the specified
host) throws UnkownHostException host host. The host can be a name
(mysite.com) or by IP address
(198.56.123.22)
static InetAddress[] Methods return an array of objects
getAllByName(String host) throws corresponding to every known IP address
UnknownHostException for the specified host.
The methods given below provide the information from an InetAddress object:
Methods of java.net.InetAddress class
byte[] getAddress() Method return an array of bytes
corresponding to the IP address, under
IPv4 this array will only be of four bytes
and for IPv6, it will be eight bytes.
String getHostName() Method returns the name of the host.
UnknownHostException is subclass of IOException and indicates that the named host could not be
successfully identified.
Example: Save the file with name “InetAddressDemo.java”
import java.net.*;
import java.io.*;
public class InetAddressDemo
{
public static void main(String ar[])
{
DataInputStream din = new DataInputStream(System.in);
String ip_name;
try
{
System.out.println("Enter a hostname or IP address :: ");
System.out.flush();
ip_name = din.readLine();
InetAddress mac = InetAddress.getByName(ip_name); //ip_name can be either IP address or host
name
System.out.println("Host Name : "+ mac.getHostName());
System.out.println("Host IP : "+ formatIP(mac.getAddress()));
}
catch(UnknownHostException uhe)
{
System.out.println(uhe);
}
catch(IOException ioe)
{
System.out.println(ioe);
}
}
static String formatIP(byte ipadd[])
{
StringBuffer ip = new StringBuffer();
for(int i=0; i< ipadd.length; i++)
{
if(i > 0)
ip.append(".");
ip.append(0xff & ipadd[i]); //0xff to turn into an unsigned integer
}
return ip.toString();
}
}
7.6 Factory methods
The InetAddress class has no visible constructors. To create an InetAddress object, we have to
use one of the available factory methods. Factory methods are simply a convention while the static
methods in a class return an instance of that class. Three commonly used InetAddress factory
methods are shown here.
Method: static InetAddress getLocalHost( ) throws UnknownHostException
Description: It returns the InetAddress object that represents the local host.
Method: static InetAddress getByName(String hostName) throws UnknownHostException
Description: It returns an InetAddress for a host name passed to it.
7.7 Instance methods
The InetAddress class also has several other methods, which can be used on the objects returned
by the methods just discussed. Some of the most commonly used methods are:
Method: boolean equals(Object other)
Description: It returns true if this object has the same Internet address as other.
Method: byte[ ] getAddress( )
Description: It returns a byte array that represents the object’s Internet address in network byte
order.
Method: String getHostAddress( )
Description: It returns a string that represents the host address associated with the InetAddress
object.
Method: String getHostName( )
Description: It returns a string that represents the host name associated with the InetAddress
object.
Method: boolean isMulticastAddress( )
Description: It returns true if this Internet address is a multicast address. Otherwise, it returns
false.
Method: String toString( )
Description: It returns a string that lists the host name and the IP address for convenience.
7.8 TCP/IP Client Sockets
TCP/IP sockets are used to implement reliable, bidirectional, persistent, pointto point, stream
based connections between hosts on the Internet. A socket can be used to connect Java’s I/O
system to other programs that may reside either on the local machine or on any other machine on
the Internet. Applets can also establish socket connections back to the host from which the applet
was downloaded. There are two kinds of TCP sockets in Java. One is for the servers, and the other
is for the clients. The ServerSocket class is designed to be a “listener,” which waits for clients to
connect before doing anything. The Socket class is designed to connect to server sockets and
initiate protocol exchanges. The creation of a Socket object establishes a connection between the
client and the server. The constructors that are used to create client sockets are:
Method: Socket(String hostName, int port)
Description:It creates a socket connecting the local host to the named host and port and can
throw an UnknownHostException or an IOException.
Method: Socket(InetAddress ipAddress, int port)
Description: It creates a socket using a preexisting InetAddress object and a port and can throw
an IOException.
A socket can be examined at any time for the address and port information associated with it with
the help of following methods:
Method: InetAddress getInetAddress( )
Description: It returns the InetAddress associated with the Socket object.
Method: int getPort( )
Description: It returns the remote port to which this Socket object is connected.
Method: int getLocalPort( )
Description: It returns the local port to which this Socket object is connected.
Once the Socket object has been created, it can also be examined to gain access to the input and
output streams associated with it. Each of these methods can throw an IOException if the sockets
have been invalidated by a loss of connection on the Net. The streams are:
Method: InputStream getInputStream( )
Description: It returns the InputStream associated with the invoking socket.
Method: OutputStream getOutputStream( )
Description: It returns the OutputStream associated with the invoking socket.
7.9 TCP/IP Server Sockets
The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on various published ports. ServerSockets are quite different from
normal Sockets. When we create a ServerSocket, it will register itself with the system as having
an interest in client connections. The constructors for ServerSocket reflect the port number that
we wish to accept connections on and how long we want the queue for said port to be. The queue
length tells the system how many client connections it can leave pending before it should simply
refuse connections. The default is 50. The constructors throw an IOException under adverse
conditions. The constructors are:
Method: ServerSocket(int port)
Description: It creates server socket on the specified port with a queue length of 50.
Method: ServerSocket(int port, int maxQueue)
Description: It creates a server socket on the specified port with a maximum queue length of
maxQueue.
Method: ServerSocket(int port, int maxQueue, InetAddress localAddress)
Description: It creates a server socket on the specified port with a maximum queue length of
maxQueue.
On a multihomed host, localAddress specifies the IP address to which this socket binds.
ServerSocket has a method called accept( ), which acts as a blocking call that will wait for a client
to initiate communications, and then return with a normal Socket which is then used for
communication with the client.
7.10 Datagram
Datagrams are the bundles of information that is passed between machines. Once the datagram has
been released to its intended target, there is no assurance that it will arrive or even that someone
will be there to catch it. When the datagram is received, there is no assurance that it has not been
damaged in transit or that whoever sent it is still there to receive a response. Java implements
datagrams on top of the UDP protocol by using two classes:
The DatagramPacket object is the data container.
The DatagramSocket is the mechanism used to send or receive the DatagramPackets.
7.10.1. Datagram Packet
The constructor specifies a buffer that will receive data, and the size of a packet. It is used for
receiving data over a DatagramSocket. Another form allows us to specify an offset into the buffer
at which the data will be stored. A different form specifies a target address and port, which are used
by a DatagramSocket to determine where the data in the packet will be sent. A still another form
transmits packets beginning at the specified offset into the data. The different constructors are:
DatagramPacket(byte data[ ], int size)
DatagramPacket(byte data[ ], int offset, int size)
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
There are several methods for accessing the internal state of a DatagramPacket. They give
complete access to the destination address and port number of a packet, as well as the raw data and
its length. Some of the most commonly used methods are:
Method: InetAddress getAddress( )
Description: It returns the destination InetAddress, typically used for sending.
Method: int getPort( )
Description: It returns the port number.
Method: byte[ ] getData( )
Description: It returns the byte array of data contained in the datagram. It is mainly used to
retrieve data from the datagram after it has been received.
Method: int getLength( )
Description: It returns the length of the valid data contained in the byte array that would be
returned from the getData( ) method. This typically does not equal the length of the whole byte
array.
7.11 Implementing Servers
To implement networking in Java, java.net package classes, give access to IP address, and a range
of methods related to TCP, UDP, and URL. IO stream classes are also used to read and write data
from and to communication channel.
A virtualstream is provided by TCP, which supports IP connection across the network. The virtual
stream supports IO stream to transport data from and to either of the connection.
There are two important classes that participate in communication. InetAddress class is used to
provide IP address of target connection. Socket class is used to create TCP connection. Once a
connection has been created, we bind both ends of a socket with their streams, and communication
will start by writing and reading data on these streams to and from remote application.
Before looking at the implementation of the server, let’s have a look on the classes of java.net that
are used to implement a server:
(i) Class InetAddress
Computer on internet is identified by IP address, that is currently in two version with different
size, in IPv4, it is 32bit long (four byte) and in IPv6, it is 128bit long (eight byte). InetAddress
provides an abstraction to access IP address that is shown in the figure below.
InetAddress
getByName ()
www.mysite.co
m
DNS
www.mysite.com
198.56.123.22
198.56.123.2
2
Figure 6
There is no constructor of this class. The class provides some static methods to create the instance
of the class, i.e. an object.
Example: Save the file with name “InetAddressDemo.java”
import java.net.*;
import java.io.*;
public class InetAddressDemo
{
public static void main(String ar[])
{
DataInputStream din = new DataInputStream(System.in);
String ip_name;
try
{
System.out.println("Enter a hostname or IP address :: ");
System.out.flush();
ip_name = din.readLine();
InetAddress mac = InetAddress.getByName(ip_name); //ip_name can be either IP address or
host name
System.out.println("Host Name : "+ mac.getHostName());
System.out.println("Host IP : "+ formatIP(mac.getAddress()));
}catch(UnknownHostException uhe){
System.out.println(uhe);
}catch(IOException ioe){
System.out.println(ioe);
}
}
static String formatIP(byte ipadd[])
{
StringBuffer ip = new StringBuffer();
for(int i=0; i< ipadd.length; i++)
{
if(i > 0)
ip.append(".");
ip.append(0xff & ipadd[i]); //0xff to turn into an unsigned integer
}
return ip.toString();
}
}
(ii) Class ServerSocket
The ServerSocket class provides the facility by which a server accepts a connections request from
clients across the network. The class creates a Socket for individual client connection. After
socket creation, an InputStream and an OutputStream will be created for communicating with
client.
The fundamental mechanism for implementing a server is to open a ServerSocket with a specific
and certain local port number. The ServeSocket will start to wait for connections. As client
generates the request to connect to this port, the connection will be established.
ServerSocket is constructed by choosing a port on the local machine. This port number should be
in the range 1 – 65536; however, ports 1 – 1023 are reserved for system services and can be used
only by the machine administrator.
Figure 7 ServerSocket
A server accepts the explicit connection request from a ServerSocket to obtain a client’s Socket
connection. As the ServerSocket is created, operating system start to accept the connections from
clients, and insert in a queue, and delete onebyone as the server call the accept() method.
ServerSocket(int portNumber) throws IOException creates a ServerSocket object that listens on
the specified port portNumber.
The ServerSocket constructor receive the value of number of connection that will be open and
received by the operating system. All these connection will be stored in a queue. Any connection
requests more than given value will be discarded. The default limit of queue is 50 to accept
connection request. This server can listen on port 1889, and have 40 outstanding connection
requests.
The methods given below allow connection to be accepted and information about the
ServerSocket to be queried.
Methods of java.net.ServerSocket class
Socket accept() throws IOException Method waits until a client makes a connection request to
the port on which this ServerSocket is registered or
listening.
void close() throws IOException Method closes the ServerSocket but will not close any
connection which have been accepted by accept() method
and not yet closed, and give instruction to operating system
not to accept new client connections. It will maintain
existing connected client connections.
int getLocalPort() Method returns the port on which this ServerSocket is
listening.
Example: Save the file with name “MyServer.java”
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer
{
ServerSocket ss;
Socket s;
DataInputStream dis;
public MyServer()
{
try
{
System.out.println("Server Started. Waiting for CLIENT Connection Request ");
ss = new ServerSocket(1889);
s = ss.accept(); //Waiting for client connection
System.out.println("CLIENT Connected");
dis = new DataInputStream(s.getInputStream());
serverChat();
}
catch(IOException ioe){
System.out.println(ioe);
}catch(Exception e){
System.out.println(e);
}
}
public void serverChat() throws IOException
{
String str;
do{
str = dis.readUTF();
System.out.println("CLIENT Message :: " + str);
}while(!str.equals("stop"));
}
public static void main(String ar[])
{
new MyServer();
}
}
(iii) Class Socket
A Socket represents a TCP connection with a machine on network. This class facilitate in
establishing the streambased channel with a remote machine.
For TCP/IP communication, there is a need to create a Socket with the remote machine. The
class Socket creates a socket and automatically established a TCP connection, and throws an
exception if it fails. Socket address is the combination of two components: one is host id, which
refers with the host name, IP address, and the port number. The port number is an integer value
that lies between 1 and 65536. In fact, on every host, there are 655636 different addresses. But
there must be a server that dynamically listens on the specified port.
Figure 8 Socket
There are two constructor of the Socket class. Creating a Socket object automatically connects to
the given host and port. As earlier stated, a server actively listens the request, but as connection
is refused an IOException will be thrown, unknown hostname can be other possibility of
connection failure.
Socket(String hostName, int portNumber) throws IOException creates a Socket object and
connects to the given host on the given port number.
Socket sckt = new Socket(“mymac”, 1889);
Socket(InetAddress hostAddress, int portNumber) throws IOException creates a Socket
object and connect to the given host address on the given port number.
InetAddress mac = InetAddress.getByName(“127.0.0.1”);
Socket sckt = new Socket(mac.getAddress, 1889);
OR
Socket sckt = new Socket(“127.0.0.1”, 1889);
Socket class methods provide the identification of remote host, port number of remote and local
host, and also give the stream for communication.
First create the Socket object to perform communications across a TCP connection. After creating
the socket, bind it with the required or corresponding stream with the help of getInputStream() and
getOutputStream() methods to communicate with the remote server. The client and server, both
will have both an InputStream and an OutputStream for the purposes of communication.
Methods of java.net.Socket class
InputStream getInputStream() Method returns an InputStream that allow streambased
throws IOException communications for TCP connections. The data written by a host
at one end; can be read by remote host from this InputStream at
other end of the connection. The method actually returns a
SocketInputStream. The SocketInputStream is a nonpublic class.
InetAddress getInetAddress() Method returns the IP address of the remote host.
int getPort() Method returns the port number of the remote host to which the
Socket is connected.
int getLocalPort() Method returns the local port number, i.e., the port number of the
Socket itself. Every TCP connection in fact consists of IP address
and port number of local machine; and IP address and port
number of remote machine, which will generally be different. A
random and unused port number is assigned to Socket at its
creation time.
Example: Save the file with the name “MyClient.java”
import java.io.*;
import java.net.*;
import java.util.*;
public class MyClient
{
Socket s;
DataOutputStream dout;
public MyClient()
{
try{
s = new Socket("127.0.0.1", 1889);
dout = new DataOutputStream(s.getOutputStream());
System.out.println("Enter the data to send to SERVER");
clientChat();
}catch(IOException ioe){
System.out.println(ioe);
}catch(Exception e){
System.out.println(e);
}
}
public void clientChat() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String st;
do{
st = br.readLine();
dout.writeUTF(st);
dout.flush();
}while(!st.equals("stop"));
}
public static void main(String ar[])
{
new MyClient();
} }
Compile both file “MyServer.java” and “MyClient.java”.
Run MyServer program in one command window.
Now server is waiting for the connection request from the client. Here accept() method will
hold it until any client generate the connection request. As any client generates a request for
connection with server, the servers accepts its request and store the client socket reference.
Run the MyClient program in another command window
As request will be generated by client, the client socket reference will be stored in Socket
object at server.
Client sends the data “Hello!” to server. Here client write the data through output stream
object, that is bind with socket at server port number.
Server receives send data and show with a prompt. In this example, server only read the data
from the input stream of client socket.
The communication will continue until client gives “stop” or forcefully terminated. As
connection terminated java.net.SocketException will fire on server machine.
7.12 Sending EMail
A socket will be created, connected to port 25, which is SMTP port number. Simple Mail Transfer
Protocol describes the format in which email messages will be sent. In UNIX OS, sendmail
daemon was already implemented to support this features.
Example: Sending Mail Using Sockets
import java.util.*;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class abc {
public static void main(String[] args) {
String host = "smtp.gmail.com";
String user = "anonymous";
String pass = "not2bgiven";
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
String from1 = "anonymous@ymail.com";
String to1 = "user@ymail.com";
String subject1 = "java";
String messageText = "Hello hw r u?";
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol.", "smtp");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
Session mailSession = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(mailSession);
try{
InternetAddress fr = new InternetAddress(from1);
msg.setFrom(fr);
InternetAddress[] address = { new InternetAddress(to1) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject1);
msg.setContent(messageText, "text/html");
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Done Mail");
}
catch (Exception err){
System.out.println("not done mail");
System.out.println(err);
}
}
}
7.13 Making URL Connections
A framework is provided by Java, using java.net package through several interfaces, classes, and
abstract classes for handling URL (Uniform Resource Locator). Using this framework, we can
easily create sum function of Web browser and can be embedded in any application.
Before discussing the concept indepth let’s have a description about two important classes given
below:
(i) Class URI
The term URI stands for Uniform Resource Identifier. It creates an instance of URI,
and are used to parse the string, and also providing various methods. Every URL is a
URI, but not every URI is a URL. On the basis of conceptual difference between URIs
and URLs, two different classes are given with their characteristics and functionalities.
(ii) Class URL
Without URL, browser cannot make out the information about web. URL identifies a
resource anywhere on the Internet. The introduction of URLs came up with WWW.
Web is a collection of protocols and different file formats. The URL is combination of
four components – the protocol, host name or host IP Address, port number and the file
path. Some protocols in use are http, ftp, gopher, and file. But HTTP is most in use and
almost everything is done by it.
A URL can optionally specify a “port”, which is the port number to which the TCP connection
is made on the remote host machine. If the port is not specified, the default port for the
protocol is used instead. For example, the default port for http is 80.
With the help of URL class’s instance some information about the resource can be accessed.
The URL always specifies a scheme, called absolute URL. A URL scheme is parsed
according to its scheme. A URL is a structure string.
There are following constructor of the URL class;
URL(String protocolName, String hostName, int portNumber, String fileName) throws
MalformedURLException creates an absolute URL from combination of all given argument.
URL(String str) throws Malformed URLException creates an instance of URL form a
complete textual specification, e.g. http://www.nsa.gov:80/index.html
URL(URL urlContext, String str) creates a new URL from an existing URL and a relative
textual URLs. E.g. urlContext is http://myserver/ and str is index.html
Example:
URL http_url = new URL(“http://www.indianrailway.gov.in”);
Methods of java.net.URL class
String getProtocol() Method returns the protocol name part of the URL as a
String, e.g. http, ftp, mailto, etc.
String getHost() Method returns the hostname as String, which is part of the
URL.
int getPort() Method returns the port number as integer, representing the
port number part of the URL. If none was specific, then 1 is
returned and the protocol default should be used.
String getFile() Method returns the file part of URL as String.
URLConnection openConnection() Method returns an URLConnection object, which
throws IOException corresponds to a protocol connection to the URL object.
Later, using this class we can access the contents of the
URL.
InputStream openStream() throws Method opens a connection to the URL and returns an object
IOException of input stream for reading its contents.
Object getContent() throws Method brings together the contents of the URL and returns
IOException it as an Object type. The actual type is depends on the
contents of the URL. If the target URL is an image then for
that an appropriate image handled is installed, then object is
of type Image, similarly, if the target URL is a text file then
appropriate text handler must be there, then object should be
returned as String.
Example: Save the file with the name “URLDemo.java”
import java.net.*;
public class URLDemo
{
public static void main(String ar[])
{
URL http_url = new URL("http://www.indianrailway.gov.in");
System.out.println("Protocol Name :: " + http_url.getProtocol());
System.out.println("Port Number :: " + http_url.getPort());
System.out.println("Host Name :: " + http_url.getHost());
System.out.println("File Name :: " + http_url.getFile());
}
}
(iii) Class URLConnection
The class URLConnection gives some additional information about a web resource. The
class provides some methods by which you can send the request to server. The class is
actually abstract. There is only constructor to create instance of URLConnection.
URLConnection (URL urlString) creates a new URLConnection object for the URL urlString.
This constructor can be called only by a subclass of the URLConnection class; and subclass will
give the implementations of the various URLConnection methods for a specific protocol.
Example:
URL http_url = new URL("http://www.indianrailway.gov.in");
URLConnection urlc = new URLConnection(http_url);
There is another way to create an instance of URLConnection, by invoking the openConnection
() method of URL class, that return an object of URLConnection.
Example:
URL http_url = new URL("http://www.indianrailway.gov.in");
URLConnection urlc = http_url.openConnection();
When working with a URLConnection object, following steps have to be taken:
1. First to obtain an object or URLConnection, call the openConnection() method of the
URL class.
2. You can set any request properties, using the given methods, if required.
3. Now connect to the remote resource by calling the connect() method.
4. After establishing the connection to the server, you can query for the header
information.
5. As a final point, now you can access the all data of resource.
7.14Advanced Socket Programming
In the following sections, we cover some advanced topic of network programming that happen in
realworld programs.
Socket Timeouts
Whenever you try to read data from a socket, the read ( ) call blocks as long as necessary to get
enough bytes. By setting SO_TIMEOUT, you can ensure that the call will never be block for more
than a fixed number of milliseconds. When the timeout expires, an InterruptedException is
thrown, and you should be prepared to catch it, but still the socket is connected. Although this read
( ) call will be failed, you can try again to read from the socket again. The next call may succeed.
There are two methods given below to set and get the timeout value.
public synchronized void setSoTimeout(int milliseconds) throws SocketException
public synchronized int getSoTimeout( ) throws SocketException
Example:
Socket s = new Socket ();
s.setSoTimeout(10000) ; // time out after 10 seconds
s.connect(….);
Timeouts are given in milliseconds. Zero is interpreted as an infinite timeout, and is the default
value.
There is one another timeout issue, that is, the constructor
can block for uncertain period of time, until an initial connection is established.
The solution for this problem to make the Socket object in the following way:
Similar option supported for ServerSocket is SO_TIMEOUT. SO_TIMEOUT is the amount of
time, in milliseconds, that accept() waits for an incoming connection before throwing a
java.io.InterruptedIOException . If SO_TIMEOUT is 0, then accept() will never time out. The
default is to never time out.
public void setSoTimeout(int timeout) throws SocketException
The setSoTimeout() method sets the SO_TIMEOUT field for the ServerSocket object. The
countdown starts as accept() is invoked. When the timeout expires, accept() throws an
InterruptedIOException . So that, set this option before calling accept() ; and the timeout value
cannot be change while accept() is waiting for a connection. The timeout argument must be greater
than or equal to zero; if it isn't, the method throws an IllegalArgumentException .
Example:
try {
ServerSocket serversocket = new ServerSocket(1148);
// block for no more than 20 seconds
server.setSoTimeout(20000);
try {
Socket s = serversocket.accept();
// handle the connection
// ...
} catch (InterruptedIOException e) {
System.err.println("No connection within 20 seconds");
} finally {
serversocket.close( );
}catch (IOException e) {
System.err.println("Unexpected IOException :: " + e);
}
Example:
// Create a socket without a timeout
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
// This constructor will block until the connection succeeds
Socket socket = new Socket(addr, port);
} catch (UnknownHostException e) {
} catch (IOException e) {
}
// Create a socket with a timeout
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
} catch (IOException e) {
}
Halfclose
Whenever server receives a request from the client application, then it always determines the end
of the request. Let's take an example, suppose last request was for writing the data to a file, and
now you just want to close the file at the end. But as you close the socket, you'll be disconnected
from the server. The halfclose is the solution of this problem. Using this, you can close the output
stream of the socket, so that, no more request goes to server, but inputstream will still be open to
receive and read the response from the server. There are two methods given below:
public void shutdownInput( ) throws IOException method is used to close or shutdown input
stream, cannot read data from the response.
public void shutdownOutput( ) throws IOException method is used to close or shutdown output
stream, cannot generate the request to the server
Example:
Socket conn = null;
try {
conn = new Socket("www.indianrailway.gov.in", 80);
BufferedReader br = new BufferedReader( new
InputStreamReader(conn.getInputStream()));
Writer out = new OutputStreamWriter(conn.getOutputStream( ), “UTF8");
out.write("GET / HTTP 1.0");
out.flush( );
connection.shutdownOutput( ); // now socket is half closed and can only
read response data
String str;
while ((str = br.readLine() ) != null)
. . .
} catch (IOException e) {}
finally {
try {
if (conn != null) conn.close( );
} catch (IOException e) {
System.out.println(e); }
}
7.15 Configuring TOMCAT server for handling URL Connections
A web application runs over the Internet. Examples of web applications are google, amazon, ebay,
etc. A web application is a 3tier (or multitier) clientserver application, usually involving a
database. Most of the web applications run on the HTTP application protocol, with browser as the
client to access an HTTP server.
A web database application requires five components, as illustrated below:
HTTP Server: E.g., Apache HTTP Server, Microsoft IIS, Apache Tomcat, and etc.
HTTP Client (Browser): E.g., MSIE, FireFox, Chrome, and etc.
Database: E.g., MySQL, Oracle, DB2, Infomix, MS SQL Server, MS Access, and etc.
ClientSide Programs: could be written in HTML Form, JavaScript, VBScript, Flash, and
etc.
ServerSide Programs: could be written in Java Servlet/JSP, ASP, PHP, and etc.
Figure 2.7 Web Database Application
A user issues a URL to an HTTP server via a web browser to start a web application. The web
application first downloads a clientside program (such as an HTML form) into the browser. The
user fills up the query criteria in the form. The clientside program sends the query parameters to a
serverside program, which queries the database and returns the query result to the client. The
clientside program displays the result on the browser.
HTTP is an asynchronous requestresponse applicationlayer protocol. A client sends a request
message to the server. The server returns a response message to the client.
Guidelines to download and install Apache Tomcat Server
Install JDK and set the PATH and CLASS PATH as given below…
My Computer>properties>advance>Environment Variables> NEW >
PATH SETTING
Variable Name : PATH
Variable Value: C:\Program Files\Java\jdk1.6.0_06\bin;
CLASS PATH SETTING
Variable Name : CLASSPATH
Variable Value: C:\Program Files\Java\jdk1.6.0_06\lib;
Now Install Apache Tomcat Server according to the steps given below and after installation
is completed Update the Class Path as
NOW UPDATE CLASS PATH SETTING
Variable Name : CLASSPATH
Variable Value: C:\Program Files\Java\jdk1.6.0_06\lib;C:\Program Files\Apache
Software Foundation\Tomcat 6.0\lib\servletapi.jar;
NOW Open your Browser and Type : http://localhost:8080/ the Click and Your Tomcat server
will run now and will open the Apache Tomcat Page.
Downloading and installing tomcat
In this section we will show the process to downloading and installing Tomcat 6 on your computer
system. The steps of downloading and installing are easy and you can learn the process very
fast. First of all learn the steps of 'How to download Apache Tomcat server on your computer'.
Click the link: http://tomcat.apache.org/download60.cgi and follow the steps according to your
requirement to achieve Tomcat server.
Step 1:
Download the jdk from your intranet’s Software Folder and then install it…
Installation of JDK:
Before beginning the process of installing Tomcat on your system, ensure first the availability of
JDK on your system program directory. Install it on your system if not already installed (because
any version of tomcat requires the Java 1.6 or higher versions) and then set the class path
(environment variable) of JDK. To set the JAVA_HOME
Variable: you need to specify the location of the java run time environment to support the Tomcat
else Tomcat server can not run.
This variable contains the path of JDK installation directory.
set JAVA_HOME=C:\Program Files\Java\jdk1.6
Note:
It should not contain the path up to bin folder. Here, we have taken the URL path according to
our installation convention.
For Windows OS, go through the following steps:
Now click on all the subsequent ok buttons one by one. It will set the JDK path.
Step 2:
For setting the class path variable for JDK, do like this:
OR
First, right click on the
My Computer>properties>advance>Environment Variables>path.
Now, set bin directory path of JDK in the path variable
Step 3:
The process of installing Tomcat 6.0 begins here from now. It takes various steps for installing
and configuring the Tomcat 6.0. For Windows OS, Tomcat comes in two forms: .zip file and
.exe file (the Windows installer file). Here we are exploring the installation process by using the
.exe file. First unpack the zipped file and simply execute the '.exe' file.
A Welcome screen shot appears that shows the beginning of installation process. Just click on the
'Next' button to proceed the installation process.
Steps 4:
A screen of 'License Agreement' displays.
Click on the 'I Agree' button.
Step 5:
A screen shot appears asking for the 'installing location'
Choose the default components and click on the 'Next' button.
Step 6:
A screen shot of 'Configuration Options' displays on the screen. Choose the location for the
Tomcat files as per your convenience. You can also opt the default Location
The port number will be your choice on which you want to run the tomcat server. The port number
8080 is the default port value for tomcat server to proceed the HTTP requests. The user can also
change the 'port number' after completing the process of installation; for this, users have to follow
the following tips.
Go to the specified location as " Tomcat 6.0 \conf \server.xml ". Within the server.xml file choose
"Connector" tag and change the port number.
Now, click on the 'Next' button to further proceed the installation process.
Step 7:
A Window of Java Virtual Machine displays on the screen
This window asks for the location of the installed Java Virtual Machine. Browse the location of the
JRE folder and click on the Install button. This will install the Apache tomcat at the specified
location.
Step 8:
A processing window of installing displays on the screen.
To get the information about installer click on the "Show details" button
Step 9:
A screen shot of 'Tomcat Completion' displays on the screen.
Click on the 'Finish' button.
Step 10:
A window of Apache Service Manager appears with displaying the running process.
Let the running process goes on.
Step 11:
After completing the installation process, the Apache Tomcat Manager appears on the toolbar
panel like shown in the below picture.
Configuring Tomcat Manager
To Configure the Tomcat Manager, there are two ways; either user can configure Tomcat directly
from the toolbar panel or can configure it from Control Panel Section.
i) Configuring from toolbar Panel
To Configure Apache Tomcat web server from the toolbar panel, you have to press 'double click'
on the appeared icon.
A configured window appears on the desktop. Now, just click on the Startup button. The
installation process will be completed.
ii) Configuration from the Control Panel
To configure the Apache Tomcat Manager, Users will have to follow the follwing steps:
Click on the Start up button select Control Panel Administrator Tool Services select
Apache Tomcat.
The following screen displays on the monitor.
Double click on the Apache Tomcat. The window of Apache Tomcat Properties appears on the
screen.
Now, Click on the start up button. The Apache Tomcat is now ready to function.
To operate it, follow the below steps of processing.
Start the Tomcat Server:
1.Start the tomcat server from the bin folder of Tomcat 6.0 directory by double clicking the
"tomcat6.exe" file.
OR
create a shortcut of this .exe file at your desktop.
2. Now Open web browser and type URL http://localhost:8080 in the address bar to test the server
3. To Stop the Tomcat Server: Stop the server by pressing the "Ctrl + c" keys.
The screen of Apache Tomcat software looks like this:
Review Questions
1. Explain how to install & configure tomcat server for handling URL connections with
example. (MDU, May’2011)
Ans. Refer Section 7.15
2.With reference to sockets, explain how client/server communication is accomplished in
java. Write a program to print the protocol, port, host and file components of a URL. (MDU,
May’2007, Dec’2007)
Ans. Client and server communication is accomplished by using Socket Progrmming. There are
two classes, plays a big role for communication, ServerSocket and Socket. Create an object of
ServerSocket class that bind on a fix port number. The method accept() will wait for any client
request. As client create an object of Socket type, and bind with a machine on given port number
by server, the server accept() method store the client socket reference.
Section 2.1 (ii) Class ServerSocket, and 2.1. (iii) Class Socket covers all the related data for this
question.
Program
URL url = new URL(“http://www.indianrailway.gov.in:80/index.html”);
System.out.println(“Protocol ::” + url.getProtocol());
System.out.println(“Port Number ::”+url.getPort());
URLConnection conn = url.openConnection();
conn.connect();
Map<String, List<String>> hd = conn.getHeaderFields();
For(Map.Entry<String, List<String>> ent : hd.entrySet())
{
String key = ent.getkey();
for(String value : ent.getValue())
System.out.println(key+”:”+value);
}
OR
URL url = new URL(“http://www.indianrailway.gov.in:80/index.html”);
System.out.println(“Protocol ::” + url.getProtocol());
System.out.println(“Port Number ::”+url.getPort());
URLConnection conn = url.openConnection();
conn.connect();
System.out.println(“Content Type::”+conn.getContentType());
System.out.println(“Content Length::”+conn.getContentLength());
System.out.println(“Content Encoding::”+conn.getContentEncoding());
System.out.println(“Creation Date::”+conn.getDate());
System.out.println(“Content Expiration::”+conn.getContentExpiration()));
System.out.println(“Last Modified::”+conn.getLastModified());
3. Describe implementation of servers. Also explain advanced socket programming with
suitable examples. (MDU, May’2012)
Ans. Refer 7.11 & 7.14
4. Write a program using Socket to receive message from a server computer.
Ans.
//Server.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
ServerSocket ss;
Socket s;
DataOutputStream dout;
public Server()
{
try{
System.out.println("Server Started \n Waiting for CLIENT Connection
Request ...");
ss = new ServerSocket(1889);
s = ss.accept(); //Waiting for client connection
System.out.println("CLIENT CONNECTED...");
System.out.println("Enter the data to send to CLIENT");
dout = new DataOutputStream(s.getOutputStream());
serverChat();
}catch(IOException ioe){
System.out.println(ioe);
}catch(Exception e){
System.out.println(e);
}
}
public void serverChat() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String st;
do{
st = br.readLine();
dout.writeUTF(st);
dout.flush();
}while(!st.equals("stop"));
}
public static void main(String ar[])
{
new Server();
} }
//Client.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Client
{
Socket s;
DataInputStream dis;
public Client()
{
try{
s = new Socket("127.0.0.1", 1889);
//Bind the DataInputStream object with client socket inputstream
dis = new DataInputStream(s.getInputStream());
clientChat();
}catch(IOException ioe){
System.out.println(ioe);
}catch(Exception e){
System.out.println(e);
}
}
public void clientChat() throws IOException
{
String str;
do{
str = dis.readUTF();
System.out.println("SERVER Message :: " + str);
}while(!str.equals("stop"));
}
public static void main(String ar[])
{
new Client();
}}
5. Discuss with example how a client application read a file from server through URL
Connection. (MDU, May’2008, Dec’2008)
Ans.
import java.lang.System,
import java.net.URL;
import java.net.URLConection;
import java.netURLEncoder;
import java.net.MalformedURLException;
import java.io.DataInputStream;
import java.io.IOException;
public class QueryURLApp{
public static void main(String args[]){
try
{
String urlString =”htt://www.jaworski.com/cgibin/echoquery”;
String extraPathInfo=”/this/is/extra/path/information”;
String queryString=URLEncoder.encode(“Query string with some special characters :
@#$%?&+”);
URL url= new URL(urlString+extraPathInfo+”?”+queryString);
URLConnection connection = url.openConnection();
DataInputStream fromURL = new DataInputStream(url.openStream());
String line;
While((line=fromURL.readLine()!=null)
System.out.println(line);
fromURL.close();
}catch(MalformedURLException ex){
System.out.println(ex);
}catch(UnknownServiceException use){
System.out.println(use);
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
6. What is Socket programming? Write a program to illustrate clientserver
Communication.
Ans. Socket programming is a mechanism by which two computers can communicate with each
other. Standard protocols are in used for the communication. To communicate with any machine
there is requirement of two components, one is address of machine on network, that can be IP or
machine name, and other is port number, on which the remote machine listen the request. For
socket programming, we create a server, which is bind with a port number. Client machine first
connect to the server with its address on network and port number to a socket. The request is
generated form the client to server established the connection. The server accepts the request and
stores the client socket reference. Then for communication to each other streams are bind with the
socket object. The data will write to and read from these stream objects on either end.
In very common words Socket is a one end point of two communication link between two running
programs running on network. A socket is bound to a port number, IP address and protocol, so that
TCP layer can identify the application that data is destined to be sent.
Steps to reading from and writing to a Socket
i. Open a socket
ii. Open an I/O stream to a socket
iii. Read from and write to the stream according to the service protocol
iv. Close the stream
v. Close the socket
The example of clientserver communication is discussed in last answer.
7. Describe how a server sends data to client? (MDU, Dec’2008)
Ans. Server sends information to clients after starting the server program; it waits for some client
to attach to its port. We chose port number for example 8189, which is not used by any of the
standard services. (Refer 2.2)
8. What information is needed to TCP Socket classes?
Ans. The Local System’s IP address and Port Number. And the Remote System’s IPAddress and
Port Number.
9. What are the two important TCP Socket classes?
Ans. Socket and ServerSocket.
ServerSocket is used for normal twoway socket communication. Socket class allows us to read
and write through the sockets.getInputStream() and getOutputStream() are the two methods
available in Socket class.
10. When Malformed URLException and UnknownHostException throws?
Ans. When the specified URL is not connected then URL throw MalformedURLException and
If InetAddress method getByname and getLocalHost are unabletoresolve the host name they
throw an UnknownHostException.