You are on page 1of 48

Java Network Programming

JAVA NETWORK PROGRAMMING


Introduction
Java is a technology that makes it easy to build network applications, which are programs executed
by multiple computers across a network. The state of that in network programming, Java has
expanded the Internet’s role from an arena for communications to a network on which full – fledged
applications run. Its breakthrough technology allows business to deploy full – fledged transaction
services that deliver real time, interactive information over the Internet.
The core API for Java includes classes and interfaces that provide uniform access to a diverse set of
network protocols. New API and tool kits have expanded the network programming functions which
enable the java network programmer to do their job rather emphatically.
Types of Java Network Applications
Java is the first mainstream programming language to provide built-in support for network
programming from its early days. Using other languages, the only way to write applications for the
network or Internet is to use the operating system independent APIs, which is very tedious task.
Whereas, using Java, writing a program that access a computer simply across the network or on the
other side of planet is easier than ever, and there is no need to go through the machine’s reference
volumes for operating system networking support.
Java provides the extensive set of core APIs using which, programmer can handle wide range of
protocols. Application Programming Interfaces (APIs) provides powerful tools for developing more
complicated networking tasks as ever before.
Using Java, we can develop following type of network applications –
 Custom Network Applications (Client – Server)
 Distributed Network Applications
 Web network Applications
 Enterprise network applications

Network
Applications

Custom Distributed Web Enterprise


Network Network Network Network
Applications Applications Applications Applications

What is Network Programming?


Network Programming is a branch of computer Science, which covers the all of writing networking
applications including reading and writing network sockets, encryption and decryption of data,
translating network protocol, sending data packets to other nodes etc. in addition to these low – level
functions, network programming also includes the design and programming of distributed
applications.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

In distributed programming, programmers distribute the task across the network. A popular way to
distribute work over a network is through RPC, that is, Remote Procedure call. Client – server
applications that use a network server for important services, such as database etc. are one popular
interpretation. We can broaden distributed computing further to indicate agents and peer – to – peer
services. The important feature of distributed computing is that it involves two or more computers
communicating with each other.
The main characteristic of network program is that they must use a computer network in anyway as
to perform their job.
Network Programs do either of one or all of the following –
 Send data across the network.
 Provide services over a network.
 Receives data over a network.
 Invoke services across a network.
Network programming includes –
 Reading and writing network sockets
 Encryption and decryption of data
 Translating network protocols
 Sending data packets to other nodes
 Providing security to the data
 And many more. . .
Terms used in Network Programming
In the network programming two terms are used frequently – Client and Server.
Client
A client is a network program residing on local host who requests for any service to the server. A
client it is started by the user and terminates when the service is complete. For example Web
browser is a network client – which requests to the Web Server to read files, view images or
download documents or images on the local PC.
Server
A server is a network program residing on the remote computer which provides services to the
Network Client on request. A server program is an infinite process. When it starts it runs infinitely,
unless a problem arises, and waits for the requests from the client. For example, Web Server is

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

network server – which runs infinitely and waits for the requests made by clients. When client made
request for any service to server, it interprets it and perform or provide services.
Protocol
A protocol is an agreed – upon way of exchanging information and service requests between client
and servers. FTP, for example, is a frequently used protocol for transforming files on the Internet.
Other operations are also possible with FTP, such as creating directories, deleting files, and so on.
What Network Programs can do?
Networking extends the power of a single computer. Network lets one computer communicate with
thousands, even millions, of other computers.
Information sharing
Network programs are principally used to share information. At their simplest form, network
programs either send or receive data through networking channels. For example, if a company has
five offices, say at Kolkata, Chennai, New Delhi, Mumbai and Banglore, then the proprietary
software may be kept at one location say at the center New Delhi. Now the distant users at other
centers, Kolkata, Mumbai, Chennai and Banglore, can use the same software, thus reducing the cost
of multiple purchase of the same software.
Parallel Computing
In parallel computing, different components work on the parts of the same single problem. And after
the completion of the particular problem they were handling return the result back. Parallel
computing extends the idea of multi tasking and multithreading.
Distributed Computing
Parallel computing does not divides its work to a single physical server rather it can distribute the
task among different servers, which is called distributed networking. In distributed networking an
application Program can be divided into different distinct parts or modules. These modules can be
executed from different servers to extend the processing capabilities of the system.
Application Services
Java is an excellent tool for implementing custom networking applications defining clients, servers
because it has multiple technologies for sending and receiving data over a network. Java network
applications can use technologies that are 100% Java and can also use non – Java technologies. Java
applications can use network connections to pass data and request services.
Web Services
Java is widely used to implement e–commerce applications. In fact, the popularity of Java is mostly
due to this reason that it provides the easy ways to develop an e – commerce applications. Applets
can provide and enhanced user interface right inside a web browser window. Servlets provide an
additional power to the web servers.
Application areas of Network Programming
Network may prove very efficient in the area of –
 Electronic mail
 Application Services
 Information sharing
 Parallel computing
 Messaging services

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Website programming
 And many more . . .
Network Programming & Java
The available network programming features in the earliest release of Java included only low – level
programming. It was possible to create sophisticated Internet applications with Java 1.0, but a Java
network programmer had to know how to do it with basic level network programming such as socket
programming.
As java has matured so has its network programming features. New API’s & new tools were added
to shield programmers from low – level network programming. These new APIs and tools use low –
level network programming “under the hood”. They provide developers with some important
benefits –
 Productivity – The new APIs and tools make developers more productive so network
applications can be written quicker and with less code.
 Maintainability – The new APIs provide high – level object models and functions libraries.
A single method can replace dozen of times of low – level networking programming,
making source code more readable.
 Robustness – Low – level network programming is error – prone. It can be complicated,
with many possibilities for subtle srrors therefore, through testing and considerable
debugging are usually required. The new APIs and tools undergo thorough testing and
debugging allowing the developer to leverage that effort. Network applications become less
fragile.
The foundation for Java networking is located in the java.net and java.io packages. The java.net
package provides the classes for implementing network applications. These classes are used to build
applications that rely upon TCP/IP and UDP. The java.io package provides classes for system input
and output through data stream serialization and the file system. Servlets and JSP allowed Java
developers to build sophisticated web applications.
The various java.rmi packages are used to develop RMI applications, a mechanism that enables an
object on one Java virtual machine to invoke methods on an object in another Java virtual machine.
Java network programming also uses other classes depending upon the application –
 The java.Security programming package provides the interface and classes for Java’s
security frame work.
 The various org.omg.CORBA packages add CORBA support to Java.
 The javax.rmi packages provide the APIs for RMI – IIOP.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

NETWORK APPLICATION MODELS


Introduction
TCP/IP is the only protocol which is used to send data all around the Internet. The purpose of
TCP/IP is to provide data communication services to users. For data communication to take place, a
computer runs a program to request a service from another program residing on the destination
computer. This is the basic idea behind network which means that two computers should connected
to the network and act as a service requester (client) or service provider (server).
Network programming is based on, generally, two models-
 Client - Server Model
 Peer-to-Peer Model
From which client-server model is much popular among the network programmers.
Client-Server Model
In a network, if any host computer wishes to receive a service from a remote computer (which
should be in the same network or connected to the Internet). Computer executes specific programs
to perform the specific job. Then the computer, to whom the request is made, performs the job for
the requesting computer. This is the basic idea of client-server model. Therefore the client-server
model consists of two types of computers-
 Servers
 Clients

Figure: Client Server Model


Client
Client computers are those who made request. A client is a program running on the local host
computer requesting the service from the server computer. A client program is finite which means it
is started by the user and terminates when the service is complete. A client opens the communication
channel using the IP address of the remote host and the well-known port address of the specific
server computer. After a channel is active, the client sends its request and receives a response. The
request-response part may be repeated for several times. At the end, the client closes the
communication channel.
Server
Server computers respond the clients, and perform jobs requested by the client.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

A server is a remote computer on a network which provides services to the clients. When it starts, it
opens the channel for incoming requests from clients, but it never initiates a service until it is
requested to do so.
A server program is an infinite program. When it is starts in runs infinitely unless a problem arises.
It waits for incoming requests from clients. When a request arrives, it responds to the request either
iteratively or concurrently.
Most of the client-server programming centers on two broad categories of applications-
 Custom Business Applications- These types of software are created by IT consultants.
These are specially designed software’s which runs on LAN.
 Internet Applications- These applications are designed to run on World Wide Web. Client-
server computing is largely used to develop e-commerce and business to business
applications which run on World Wide Web.
Characteristics of Client-Server Model
 Services- Servers respond to service requests from clients.
 Separate Processes- Servers and clients run in their own distinct processes. Those processes
do not need to run on separate machines to qualify as client-server. Client and server could
instead operate in their own addresses spaces on the same machine.
 Asymmetrical Relationship- Clients and servers are not peers they cannot swap the roles.
Clients initiate communication by requesting a service. Servers fulfill those requests.
Between service requests, servers passively wait for clients to request a service.
 Loose Coupling- Servers encapsulates their functionality. A client can initiate a service in
several ways such as making a remote procedure call or passing a message to the server.
Implementation details for service are unknown by client.
 Location Transparency- The server process can run on the client machine or it can run on a
remote machine.
 Scalability- This is done in two ways- distributing the process load across more processors
or through techniques like multithreading. The client-server system can be scaled by
distributing the processing across multiple machines- "distributed computing ". Clustering
is a form of distributed processing that uses multiple machines to work together as a single
system, sharing the same namespace. This improves both the scaling and reliability. If a
machine in a cluster crashes, other servers can redistribute the load. The load is balanced
across the machines in the cluster to provide the maximum performance.
Applications of the Client-Server Model
Client-server is a useful model for sharing and managing resources on a network. Some common
examples of client-server model applications are-
 File Servers – The network file server manages the network. It acts as a shared
repository for different information files such as, documents, image files, etc.
 Database Servers – In the network client passes SQL requests to database servers. The
database server than perform the queries and returns the result back to the client.
 Proxy Server – Proxy servers are used to manage Internet connections for an
organization. They are often implemented as part of a security firewall denying those
behind it access to the Internet and more importantly access from the Internet to an
internal network.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Email Servers – Email servers provide 24–7 reliability. Client workstations can fetch
their email by making calls to the email server with the POP3 and other email protocols.
 Application Servers – Application servers provide business logic services, often through
components, such as Enterprise Java Beans (EJB). Application servers frequently offer
additional features, such as transaction management and load balancing.
 Print Servers – Print Servers allow multiple workstations to access shared printer. Print
Server also allow for remote administration of servers, such as cancellation of print jobs.
Client-Server Mechanism
A client initiates a request of some sort and the server provides an appropriate response. The same
process can be a client or a server; it can even be both at the same time. For example, client A can
invoke a method on server B. Server B can then invoke a method on another server, server C. Which
role a process plays, client or server, depends upon the relationship between the two processes for a
particular context. Change the context and their respective roles can change.

1 1

2 2

Figure: Client-Sever Mechanism

1. REQUEST: Client initiates a connection, made request for the service to server.
2. RESPONSE: Server accepts the request, respond to the client and provide the services to
clients.
Sockets
Java programs communicate through a programming abstraction called socket. A socket is one end-
point of a two-way communication link between two computers (or programs) running on a network.
A socket is bound to a port number so that the TCP layer can identify the application that data is
destined to be sent.

Client Socket Server Socket


on client side on server side

P P
O O
R R
T T

Figure: Sockets and Ports

Ports

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

One mechanism that is commonly used by network protocols, and in particular the Internet transport
layer protocols, is port addressing. Every network service is associated with one or more ports on
one or more IP interfaces of its host device. Typically, integer numbers are used to identify different
ports. In order to contact a network service, it is therefore necessary to provide both the IP address of
its host, as well as port number it is using.
Client-Server: The Architecture
One of the most difficult things about developing client-server applications is deciding how to split
the work between client process and server process.
Single – Tier Architecture

User Interface
Processing
Reading/Writing
Data
Figure: Single – Tier Architecture

Some applications are developed to run on a single computer.


In these types of applications all functionalities are embedded with in the same layer, such as user
interface, processing, data manipulation, etc.
Such type of architecture is called single – tier systems.
Two-Tier Architecture
Before the invention of PC’s, applications were used to run on mainframe based client-server
environment. These applications used a “thin” client and “thick” or “fat” server. The functionality
of the client-server system was predominantly on server side.

Submit Input

Display Output

Business Rule Data Access User Interface


On Server On Clients
Figure: Two – Tier Architecture

The most important features of traditional mainframe system are-


 Dumb terminals connected over communication links, to mainframe computers.
 Application logic resides in the mainframe application.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 The terminal provided a character based user interface.


 The mainframe application could use the various character sequences to position output. A
“screen scrapers” program could read data from the terminal and return it to the
mainframe. Simpler program could just use simple character streams for input and output.
Layers of Two -Tier Architecture

User Interface Layer

Business Rule, Data Access Layer

Figure: Layers of Two – Tier Architecture

The approach of these applications is centralized in which multiple users are allowed to work
simultaneously. Clients provide only user interface and rest of all the processes are run on server
side. All the services and data access provided by server is shared by all the users working on the
application.
Three – Tier Architecture

Clients Application Server Database Server


Figure: Three-Tier Architecture

Three-tier architecture divides the application into three set of services-


 Presentation Layer – User Interface Tier
 Business Logic Layer – Business Rule Tier
 Data Layer – Data-Store Tier
Three-tier applications can conserve database server resources by reducing the number of concurrent
database connections. Once we encapsulate business rule services into components and move the
components to an application server, the database server no longer needs separate connections for
each client. Instead, it needs a separate connection for each running instance of the business rule
component. Users no longer require separate logins. They don’t even need database drivers. This not
only saves data resources, it also eases database account maintenance and improves data security.
Layers of 3–Tier Architecture

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 User-Interface Tier – This tier handles the user interface logic. This is normally on the
client side.
 Business Rule Tier – This tier handles all of the business rules logic and validates user
input from user interface tier.

User Interface Layer

Business Rule Layer

Data Access Layer

Figure: Layers of Three-Tier Architecture

 Data-Store Tier – This tier is concerned with the storage and retrieval of data from
databases.
Advantages of 3-Tier Architecture
 Moving business rule components to an application server can boost performance.
 Multiple application servers can take advantage of load balancing and improve system fault
tolerance.
 Changes to business rule can migrate to a small number of application servers instead of a
large number of workstations.
 This also provides better code encapsulation allowing different people or even companies to
implement each tier.
Multi – Tier Architecture
Multi-tier or n-tier architecture takes the partitioning of application services even further. They
divide the business rule services tier into collaborating tiers – one for business rule processing that
supports the user interface and the other for business rule processing that integrates and manipulates
data.

UI
Oriented
Business
Rule

Clients Business Rule Application Server Database Server


Figure: Multi -Tier Architecture

 Presentation Layer – User Interface Tier


 Presentation Logic Layer – User Interface oriented Business Logic Tier

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Business Logic Layer – Business Rule Tier


 Data Layer – Data-Store Tier
The central idea in multi-tier architecture is to keep the services physically close to data they work
with. The difference between three-tier and multi-tier appears trivial (of little importance). We
simply partition the business rule service tier. However, this provides considerably more flexibility.
Multi – tier applications scale well because multi – tier architecture is a component based
architecture.
Multi-tier architecture lets us put UI – Oriented business rule components or work station. UI –
oriented business rule components are excellent candidates for Java Beans. The Java Beans API lets
developers create reasonable, platform – independent components that can be combined into applets,
applications, or composite components. Keeping UI – oriented business rule components on the
workstation keeps them close to the client, improving the performance of the user interface.
Data oriented business rule components are best deployed on the data base server or a separate
application server. This makes them excellent candidates for Enterprise Java Beans (EJB). The EJB
API extends the idea of Java Beans to the realm of distributed programming. With the EJB
technology, components can be deployed on a remote server and then accessed as if they were
installed locally.
The multi – tier architecture is flexible about the placement and the presence of application servers.
A small enterprise might select to use their data – base servers as an application server. As the
enterprise grows, the system can scale by adding a separate server to take over as the application
server task.
Layers of n–Tier Architecture
 Presentation Layer - This handles the UI logic, which includes the actual presentation of
screens and collects information.
 Presentation Logic Layer - This layer handles business rule logic that supports the UI. For
example, validation of user input.
 Business Logic layer - This is responsible for data manipulation and integration. It can
combine data from SQL databases with flat files or even Internet resources.
 Data Layer - This layer handles the storage and retrieval of data from databases, files, and
other data sources.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

1 - User Interface Layer

2-UI-Business Rule Layer

3 - Business Rule Layer

4 – Data Access Layer

Figure: Layers of Multi -Tier Architecture

Advantages of n-Tier Architecture


 The central idea in multi-tier architecture is to keep the services physically close to data they
work with.
 Multi-tier architecture lets us put UI – Oriented business rule components, which are
excellent candidates for Java Beans which let us to create reasonable, platform – independent
components.
 Data oriented business rule components are an excellent candidates for Enterprise Java Beans
(EJB) which provides the facility of distributed programming.
 Multi – tier is component based architecture. Therefore business logic services that support
the UI can remain physically close to the client. Remaining application services can scale as
additional resources become available.
 The multi – tier architecture is flexible about the placement and the presence of application
servers.
The Peer – to – Peer Model
A Peer – to – peer network program brings two or more computers into direct communication so
they interact with each other without involving other computer in their workflow. The computers can
shift roles i.e. they can cut as client, server or both. Therefore they can’t be adequately described in
the client – server model.
The classic example of peer – to – peer networking is the telephone system. One party initiates a
telephone conversation. After answering the call, there is no asymmetry i.e. the parties can both
speak, listen or do both at the same time. Either party can terminate the telephone conversation at
any time.
The Hybrid Model
The hybrid model is a natural extension to the strict peer-to-peer model. It is popular for programs
like Napster and ICQ. The typical case uses a server to locate available peers. Once the peers are
connected, the server is removed from their communications loop. The peers communicate directly.
The role of server, in this case is to provide a directory service.
Instant messaging services, like the ICQ are a good example of hybrid peer-to-peer model. The
client software can initiate surges of the remote server’s database to find users. Once the user is

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

found to share messages, communication becomes peer-to-peer. Adding a limited client-server


interaction for directory services increases the flexibility of the peer-to-peer model.

INTERNET ADDRESSING
Internet
The Internet is a network of networks, all of which agree to communicate using a standard set of
protocols. Several Inter-networking technologies were developed in the 1970’s and 1980’s. One of
these was the collection of protocols standard by the Internet Engineering Task Force (IETF).
The Internet Protocol (IP) is the core of this protocol suite. The basic communication model of the
IP is that of a connection-less, best-effort packet service. Internet nodes wishing to send data across
the network to a destination node must first breakdown data into smaller data-segments called
packets. Each packet is then transmitted individually on a hop-by-hop basis towards the destination
node. Internet nodes performing forwarding functions are called routers. Packets are forwarded with
best effort so they may not be lost, get corrupted or arrive out of order at the destination.
The three basic functions of Internet communications are addressing, naming and routing.
 Addressing – An Internet address uniquely identifies the location of an Internet node. In a
sense, an Internet address is like a traditional mailing address. If a node moves to a different
network, its address will change. Moves within same network may, or may not require a
change in address. This is similar to moving within a building with un-numbered apartments,
versus moving within a neighborhood.
 Naming – Names provide a location-independent reference to Internet nodes. Unlike Internet
address that is essentially large integer numbers; names may contain letters and certain
symbols making them easier for human to remember. In order to communicate with an
Internet node identified by a name, an application must lookup (resolve) the Internet address
for that name. The operation is similar to using a phone book to lookup the number of a
person by using his or her name. Unlike printed phone books, the Internet name directory can
be changed as often as needed, therefore when a node moves; its name-to-address listing may
be updated immediately. Although the IP does not mandate any particular mechanism or
protocol for name-to-address resolution, the Domain Name System (DNS) has become the
de-facto Internet Naming Mechanism.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Routing – Internet nodes forwards their destination address using local routing information.
Internet nodes used to forward packets between destination are called routers. Routers may
be statically configured, or may compute their forwarding table dynamically using one of
several dynamic routing protocols. The advantage of computing rotes dynamically is that the
network can recover from failures by redirecting traffic over alternative paths. Internet
routing decisions are hidden from users and can only be modified with administrative
privileges,
java.net.INETADDRESS
Java encapsulates the concept of IP address in a class, which is part of the java.net package and is
called InetAddress. This class allows to manipulate a 32-bit IP address in a more high level fashion
than by just using a single 32-bit integer. Class InetAddress essentially lets one to convert a textual
Internet address of the form host.subdomain.domain into an object representing that address.
InetAddress class contains following methods –
 getByName() : java.net.InetAddress
 getAllByName() : java.net.InetAddress
 getLocalHost() : java.net.InetAddress
 getHostName() : String
 getAddress() : byte[]
 getHostAddress() : String
 isMulticastAddress() : Boolean
getByName()
The most commonly used method is getByName() with the following signature –
static InetAddress getByName(String host) throws UnknownHostException
This method returns an InetAddress object encapsulating the result of a DNS lookup on the string
domain argument. For example, invoking getByName (“myweb.com”) will return an InetAddress
instance storing the domain name “myweb.com” as well as the resolved address
("204.148.170.161”).
If the string method argument represents an IP address in dotted decimal notation then the object
created will encapsulate the given address. For example, invoking getByName(“204.148.170.161”)
will create an InetAddress.
If the domain name can not be resolved the java.net.UnknownHostException is thrown. The
method may also throw a runtime SecurityException, in case if a Java Security Manger has been
installed, and the code-base has not been given the resolve permission.
getAllByName()
The second method is similar to the previous method with the difference that all lookup results are
returned. This method may also throw a runtime SecurityException if a security manager has been
installed and the resolve permission has not been granted.
static InetAddress[] getAllByName(String host) throw UnknownHostException
getLocalHost()
The third and final method does not take any argument and returns an InetAddress object
representing the IP address and name of the host executing the JVM. Most modern operating
systems support a look-back network interface that is usually assigned the special IPAddress
127.0.0.1 and is commonly mapped to the name “localHost”.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

This method may throw the UnknownHostException. In this case this exception is used to signal an
error in obtaining a local IP address.
Read Methods
The InetAddress class provides four read methods for querying the state of instances. The methods
do not throw any exceptions since all possible exceptions would have been thrown by previous
methods.
 String getHostName() – Returns the domain name of this address, for example, yahoo.com.
 byte[] getAddress() – Returns the address 32-bit value as a 4 byte array in network byte-
order, for example,
new byte[] {(byte) 0xCC, (byte) 0x94, (byte) 0xAA, (byte) 0xA1}
 String getHostAddress() – Returns the dotted decimal string representation of this address,
for example, 204.148.170.161.
 boolean IsMulticastAddress() – Returns true if this is a multicast address.
In addition to the above four methods, the InetAddress class overrides the following default
java.lang.Object methods –
 int hashCode() – Returns an integer (32-bit) value representing the IP address.
 boolean equals() – returns true if he argument is an InetAddress instance encapsulating the
same IP address.
 String toString() – Returns a string representation of this address. The current implement
returns a string containing both the dotted decimal IP address representation and the host
name.
Example code displaying usage of getByName() and getAllByName() –
//InetAddExample.java
import java.net.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddExample{
public static void main(String[] args) throws UnknownHostException{
InetAddress address = InetAddress.getByName(“starware.com”);
System.out.println(address);
InetAddress sw[] = InetAddress.getAllByName(www.yahoo.com);
for(int i=0;i<sw.length;i++){
System.out.println(sw[i]);
}
}
}

Example code displaying usage of Local Host Methods


// LocalHostExample.java
import java.net.*;
import java.net.InetAddress;
public class LocalHostExample{
public static void main(String[] args){
try{
InetAddress address = InetAddress.getLocalHost();
String hostAddress = address.getHostAddress();

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

String hostname = address.getHostName90;


System.out.println(“Local Host Address: ” hostAddress);
System.out.println(“Local Host Name: “ + hostname);
}catch(UnknownHostException ex){
System.out.println(“Trouble : “ + ex.getMessage());
}
}
}

JAVA TCP PROGRAMMING


Transmission Control Protocol
The Transmission Control Protocol (TCP) is a transport layer protocol. TCP provides reliable,
full-duplex connections and reliable service by ensuring that data is resubmitted when transmission
results in an error. TCP enables two network entities to establish a bi-directional communications
channel for reading and writing streams, that is, sequence of bytes. For example, a Web Browser
will communicate with a Web Server over a TCP in order to send a request for a particular page and
receive the content of that page. The TCP protocol guarantees that bytes will be delivered to
recipient in the order written by the sender. The structure and meaning of the bytes exchanges is
typically defined by an application-layer protocol – HTTP – the Hyper Text Transfer Protocol.
Once the message arrived at the correct IP address, TCP’s main task is error checking to make sure
that the information received by the computer on a TCP/IP network is exactly the same information
that was sent to it by another computer on the network.
In addition to providing reliable full-duplex channels, TCP also performs an important Internet
“community” service. In most networks, the collective maximum rate in which network participants
can send data into the shared network generally exceeds the network’s bandwidth. This problem is
known as network congestion. It is therefore important to provide some mechanism to control the
congestion. TCP performs congestion control by controlling the rate with which data is written to the
network in response to network conditions. The distributed algorithm used guarantee that competing
TCP streams will get a “fair share” of the network bandwidth.
TCP performs an additional service called flow control. In any stream based communication, it is
possible for one side to send data at a rate that exceeds the receiver’s capability to process that data.
This is different from congestion control because it involves limitation in the receiver’s capability
rather than network’s capability. The TCP protocol performs flow control by allowing the receiving
end of each unidirectional channel to control the rate in which the sender writes data.
Functions of TCP
The main issues that TCP must address are –

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Stream Segmentation – TCP breaks the stream into segments, because the IP protocol only
supports transmission of limited size packets. It is preferable to transmit packets containing
the largest possible payload to reduce the cost of transmitting the IP and TCP headers.
 Stream Reassembly – Sometimes the TCP streams that are transmitted as IP packets may
arrive at the destination in different order than the order sent. TCP must be able to handle
out-of-order delivery and still reassemble the data in the order transmitted. TCP addresses
this problem by counting the number of bytes transmitted in the stream and identifying each
of the first stream byte it carries.
 Handling Packet-loss - IP packets carrying segments of the stream may be lost in the way.
TCP must be able to detect that a packet has been lost and arrange retransmission.
TCP deletes packets loss by positive receiver acknowledgements. When a TCP packet
arrives, the receiver’s TCP protocol implementation will send a TCP packet to the sender
acknowledging receipt. If the sender fails to receive acknowledgement by a certain deadline,
it will retransmit the packet.
 Data Corruption Detection - The IP protocol only protects its own header and does not
make any guarantees on the payload contents. It is therefore possible that one or more bits in
the payload may be corrupted due to transmission error.
For this payload’s summary is computed and stored in the packet’s header. The receiver of
the packet then independently computes the summary of the data received, using the same
algorithm and compares it to summary stored in header. This algorithm protects against all 1-
bit errors and some multiple bit errors.
 Throughput Efficiency – The design of a reliable streaming channel is further complicated
by the requirement for efficiency. For this one could develop a stop and wait design in
which the sender transmits the next packet of data in which the sender transmits the next
packet of data every, certain-milliseconds until an acknowledgement is received. But in this
design the maximum throughput is limited by the communication round-trip overhead.
TCP addresses this problem by using a technique called sliding-window. In this approach,
the receiver instructs the sender on the maximum number of unacknowledged bytes that can
be transmitted (the window). Once the sender has transmitted a window-size full of data, he
must wait for a receiver acknowledgement. When it has been received, the sender can send
out as much data as was acknowledged. This mechanism increases the concurrency of
operation as well as enables receivers to the control the flow of transmission.
Java TCP Programming
The programming model of TCP communication in Java, rely completely on the sockets and ports.
Because TCP is a stream protocol, it allows to send arbitrary amount of data rather rely on class to
encapsulate data within TCP packets.
Sockets
Java programs communicate through a programming abstraction called socket. A socket is one end-
point of a two-way communication link between two computers (or programs) running on a network.
A socket is bound to a port number so that the TCP layer can identify the application that data is
destined to be sent.
Mostly, applications do not care how data is actually transmitted in the network. Applications
identify the address of the peer entity and then use sockets interface to read and write data from and
to the peer. Sockets include the implementation of network and transport layer protocols providing
applications with a simple read/write interface.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

Because sockets are just programming abstractions for network protocols, the other side of the
connection does not have to use them. Sockets don’t use any additional communication mechanism
other than that provided by the encapsulated protocol.
The socket abstraction was developed in the first networked version of UNIX developed at the
University of California at Berkeley by Bill Joy. Those sockets are therefore, also known as
Berkeley sockets. Traditionally, sockets abstraction as a core language library feature in order to
support portable, cross-platform network programming.
Ports
One mechanism that is commonly used by network protocols, and in particular the Internet transport
layer protocols, is port addressing. Every network service is associated with one or more ports on
one or more IP interfaces of its host device. Typically, integer numbers are used to identify different
ports. In order to contact a network service, it is therefore necessary to provide both the IP address of
its host, as well as port number it is using.
Each published protocols are assigned with certain port number, what are called “well-known port
numbers”. The advantage of this solution is that an additional port-directory mechanism is not
needed. Every standard Internet application requests a port number from the Internet Assigned
Numbers Authority (IANA). For example, tcp:23 port number is assigned for FTP, tcp:80 for
HTTP, etc.
IANA reserves ports 1 – 1023 for well-known services. Less popular or platform-specific services
can still request registration of ports in the range of 1024 – 49151. If a service is meant for Internet
deployment, then users can just pick up a port number that is not already assigned. Both the client
and server must then be configured to connect to and bind to the given port. Finally, ports in the
range 4915 – 65535 are typically used for port assignment.
Stream Sockets

[11] “Hello, I’m Fine”


” [9] Get I/O
Stream

[10] “Hello, How are You”


Server
[6] Return Program
Client accept()
Program
Socke
TCP
t

[7] TCP [1] create(4567)


Protocol [2] accept()
[8] Get I/O
[3] create [5] Create
Stream
(“server”,
4567)
Socke

TCP
TCP

[4] TCP Connection


t

ServerSocket

Figure: Use of Sockets to establish two-way communication

The diagram illustrates the use of sockets to establish two-way byte-streaming communication. On
the left hand side of diagram is a Java-client program wishing to connect to the server on the right.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

In order to receive remote connections, the server program must first create a ServerSocket. A
server is a receiver of incoming connection requests. Each protocol has its own server socket type.
For a TCP communication following steps are involved –
 The server program creates a TCP server socket bound to port 4567.
 At this point the server invokes the accept() method on the server socket and blocks waiting
for the first client connection.
 Java client program creates a regular socket with the same name or address of the server host
as well as the port number of the server program. This protocol type of client socket must
match the protocol type of the server.
 Upon creation, the socket object attempts to establish communication with its peer using the
TCP protocol.
 Once the TCP handshake is complete, the server socket creates a socket to model the server’s
side of the TCP communication.
 This is returned as the result of the blocked accept() call.
At this point, the client and the server are each in possession of a socket object and in bi-directional
link. Now in order to transmit information, both the client and the server must obtain an input and
output stream from the socket object (steps 8 and 9).
Package java.net
The Java language supports TCP programming through the java.net.Socket and
java.net.ServerSocket classes. Java clients connect to TCP servers by creating instances of the
java.net.Socket class. Similarly, Java servers listen for java clients by creating
java.net.ServerSocket class. Connections are configured through the methods of these two classes.
Actual network communications, however, are performed using the java.io package streaming
classes.
The diagram below illustrates the main operations of the Java streaming socket classes. The Java
TCP server, on the right, accepts TCP connections by creating a java.net.ServerSocket instance
bound to a particular port. When a ServerSocket establishes a connection with a TCP client, it creates
a java.net.Socket instance encapsulating that connection and returns it to the server program. The
java.net.Socket object returned is bound to an ephermal port number that is different from the one
the ServerSocket is listening to. The server retrieves the socket’s input and output streams and
effects communication by implementing some protocol.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

java.n
rSock
Serve
et

et
TCP create(port)
Connect accept() call

create return
(server, to
Java Java

Socke

Socke
java.n

java.n
port) accept()

et

et
Client t

t
TCP Server

create creates

Outpu
tStrea
java.i

java.i
Input
Strea
m

m
o

Outpu
tStrea
java.i

java.i
Input
Strea
m

m
o

o
Figure: Main Operations of Java Streaming Classes

On the client side, TCP connections are established through instances of java.net.Socket associated
with a TCP server on the given host and port. Once the client Socket has established a TCP
connection, retrieves the socket’s input and output stream, effects communication.
Client-Side TCP Programming
The java.net.Socket of a java.net package implements client side of a two-way connection between
Java program and another program on the network. By using this class instead of relying on native
code, Java program can communicate over network in platform independent fashion.
Creating a Socket
In order to establish a connection with a network server one must have the address of the server’s
host, and port number to which the server is bound. The java.net.Socket class provides a
constructor, which takes an IP address and port number and attempts to establish a connection. The
signature of this constructor is as follows –
Socket(InetAddress, int port) throws IOException;
The constructor returns only after the connection has been established, that is, once the TCP three-
way handshake has been completed. Hence the constructor must signal errors in establishing the
connection. Throwing the java.io.IOException exception signals such communication error.
A connection attempt may fail for multiple reasons. For example, either the remote IP address may
not reachable or IP address may be reachable but server may not be bound to the specific port
number on the given address. Although the signature of the constructors only declares the
java.net.IOException, users wishing to programmatically determine the reason for the connection
failure, can try to catch the following java.io.IOException subclasses –
 java.net.NoRouteToHostException – This indicate that the client or server host is not
connected to the network, or that there is no path from the client’s network to the server’s
network due to some failure.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Java.net.ConnectException – The network of the remote server can be reached, but either
no host has been assigned the specified address, or a host is reachable but no application is
listening to the specified port on this protocol used.
Additionally, the constructor may throw the runtime exception java.lang.SecurityException if a
security manager has been installed, and the connect action has not been provided for the target IP
address and port.
A similar constructor is provided for use with host names, or IP addresses represented as Strings.
The signature is as –
Socket(String host,int port) throws IOException;
This constructor may also throw an additional IOException subclass called
java.net.UnknownHostException if the host name can not be resolved, or string representation of
the IP address is invalid. There is another equivalent constructor with the previous constructor,
which is much more convenient –
new Socket(InetAddress.getByName(host),port);
Example of a simple program demonstrating Socket Creation –
//SimpleClient.java
import java.net.*;
import java.io.*;
public class SimpleClient{
public static void main(String[] args){
String host = “sap_server”;
Int port = 1234;
try {
System.out.ptintln(“Attemting to connect to a TCP service on host “
+ host + “and port: “ + port);
Socket s = new Socket(host,port);
System.out.ptintln(“Connection Esteblished . . .“);
}catch(UnknownHostException ue){
System.out.ptintln(“Trouble: “ + ue.getMessage());
}catch(IOException ioe){
System.out.ptintln(“Trouble: “ + ioe.getMessage());
}catch(SecurityException se){
System.out.ptintln(“Trouble: “ + se.getMessage());
}
}
}

Reading - Writing Socket


Connection oriented sockets are an abstraction for a byte-stream communication between two
network programs. Therefore the most important methods of the Socket class are the ones that
permit users to actually use instances for communication. The Socket class provides two methods,
one for obtaining an input stream for reading bytes and one for obtaining an output stream for
writing byte-stream to the output stream. The streams are represented as java.io.InputStream and
java.io.OutputStream instances encapsulating the communication stream. An exception
java.io.IOException will be thrown in this case. The signatures are –
java.io.InputStream getInputStream() throws IOException;
java.io.OutputStream getOutputStream() throws IOException;

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

Once the input and output streams for the socket have been obtained, it is up to application to
determine the contents of communication.
Getting Socket Information
Connection oriented sockets encapsulate a connection to a network peer or remote host, therefore,
they may be characterized by set:
<local_address, local_port, remote_address, remote_port>
The four methods for querying the Socket local and remote addresses and port numbers are –
InetAddress getInetAddress() throws IOException;
int getPort() throws IOException;
InetAddress getLocalAddress() throws IOException;
int getLocalPort() throws IOException;
Terminating socket
As file objects also consume finite operating system resources. An open socket keeps a local port
busy, and in most cases uses at least one native operating system file handle. Both port numbers as
well as file handlers are limited and therefore it is very important to explicitly close sockets when the
connection is no longer needed. The close(0 method requests asynchronous termination of the socket
connection.
The close() method will return immediately, even if data written before invocation has not
completed transmission. The default semantics of the method invocation are that delivery of data
written before invocation will continue to be attempted until successfully delivered. It is possible to
limit the maximum duration of pending data delivery using the setSoLinger() method.
void close() throws IOException;
Once a socket has been closed the input and output stream may no longer be used. An attempt to
read and write data from input stream and to output stream will result in IOException. An attempt to
read and write data from input stream and to output stream will result in IOException. An
alternative way to close a socket is to invoke a close(0 method on either the input or only the output
directions of the connection. The two methods for effecting such behavior are –
void shutdown Input() throws IOException;
void shutdown Output() throws IOException;
Example code illustrating reading/writing through Socket
The example program implements a client, EchoClient, that connects to the EchoServer. The
EchoServer simply receives data from client and echoes it back.
EchoClient creates a socket thereby getting a connection to the Echoserver. It reads the input from
the user on the standard input stream, and then forwards that to the EchoServer by writing the text to
the socket. The server echoes the input back through the socket to the client. The client program
reads and displays the data passed back to it from the server.
//EchoClient.java
import java.net.*;
import java.io.*;
public class EchoClient {
public static void main(String[] args) {
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

try{
echoSocket = new Socket(“sap_server”,7);
out = new PrintWrite(echoSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream());
}catch(UnknownHostException ue) {
System.out.ptintln(“Trouble: “ + ue.getMessage());
}catch(IOException ioe){
System.out.ptintln(“Trouble: “ + ioe.getMessage());
}catch(SecurityException se) {
System.out.ptintln(“Trouble: “ + se.getMessage());
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(system.in));
String userInput;
while(!(userInput = stdIn.readLine()).equals(“quit”)) {
out.println(userInput);
System.out.println(“Echo: “ + in.readLine(0);
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
EchoClient both writes to and reads from its socket, thereby sending data to and receiving data from
the EchoServer.
The three statements in the try block of the main method are critical. These lines establish the socket
connection between the client and the server and open a PrintWriter and a BufferedReader on the
socket.
echoSocket = new Socket(“sap_server”,7);
out = new PrintWrite(echoSocket.getOutputStream(),true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream());
The first statement in this sequences creates a new Socket object and names it echoSocket. The
Socket constructor used here requires the name of the machine and the port number to connect, the
example program uses the host name “sap_server”. This is the name of a hypothetical machine on
local network. The second argument is the port number. Port number 7 is the port on which the
EchoServer listens.
The second statement gets the socket’s output stream and opens a PrintWriter on it. Similarly, the
third statement gets the socket’s input stream and opens a BufferedReader on it.
The example uses readers and writers so that it can write Unicode characters over socket.
To send data through the socket to the server, EchoClient simply needs to write to the PrintWriter.
To get the server’s response, EchoClient reads from the BufferedReader.
The next part of the program is the while loop. The loop reads a line at a time from the standard
input stream and immediately sends it to the server by writing it to the PrintWriter connected to the
socket.
String userInput;
while(!(userInput = stdIn.readLine()).equals(“quit”)) {
out.println(userInput);
System.out.println(“Echo: “ + in.readLine(0);
}

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

The last statement in the while loop reads a line of information from the BufferedReader connected
to the socket. The readLine method waits until the server echoes the information back to the
EchoClient. When readLine returns, EchoClient prints the information to the standard output.
The while loop, continues until the user types an end-of-input character. That is, EchoClient reads
input from the user, sends it to the EchoServer, gets a response from the server, and displays it, until
it reaches the end-of-input. The while loop then terminates and the program continues, executing the
nest four lines of code –
out.close();
in.close();
stdIn.close();
echoSocket.close();
These lines of code fall into the category of housekeeping. A well behaved program shoul always
cleans up after itself. These statements close the readers and writers connected to the socket and to
the standard input stream, and close the socket connection to the server. The order here is important
because any streams connected to the server should be close before the socket.
Server-side TCP Programming
In order to accept network connections a Java program must create an instance of
java.net.ServerSocket. Server sockets are not directly used to perform any network communication.
Instead, they act as factories that create a java.net.Socket object for every incoming TCP
communication request. Programs create the server socket, bind to a specific port on one or more
interfaces, and then invoke the blocking accept() method.
Creating ServerSocket
The basic ServerSocket constructor takes a single argument, the TCP port number used in binding. If
the constructor returns without throwing an exception then the server socket has successfully bound
to the requested TCP port. The constructor may fail due to an I/O error, or due to a security error.
The signature of the constructor is –
ServerSocket(int port) throws IOException,SecurityException;
Port is not permitted to listen more than one process at the same point of time. Therefore, if any
process has created a socket bound to the specified port an IOException will be thrown.
An additional constructor is also provided, which permits users to specify the size of the connection
backlog queue. Because the client connection requests happen asynchronously, it is possible that
new requests will be received before the server program has been able to invoke the accept()
method. In such cases, the requests are placed in a queue, and retrieved on subsequent accept()
invocations. This constructor throws the same exceptions as the basic constructor, that is,
IOException and SecurityException. The signature of this constructor is as follows –
ServerSocket(int port, int backlog) throws IOException, SecurityException
The third and final constructor permits user to bind to a particular local interface. Port numbers are
assigned per protocol per interface. The previous two constructors attempt to bind program to the
specified port on all available interfaces. The signature of this constructor is –
Server Socket (int port, int backlog, Inet Address bind Address)
throws IO Exception, Security Exception
Accepting Sockets
The main task of server socket is to receive incoming connection requests and generate a
java.net.Socket object that encapsulates each request. Incoming connections are queued until the
program retrieves them one at a time by invoking the accept() method. The accept() method takes no
arguments, and returns the next connection in the queue.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

If no connection requests are pending then the method blocks until a request is made, or the
optionally specified connection timeout has expired. The method may throw an IO Exception if the
Server Socket has been closed, or a communications error is encountered. The method may also
throw Security Exception if the incoming connection originated from a host/port not covered by an
accept socket permission.
//SimpleServer.java
import java.net.*;
import java.io.*;
public class SimpleServer{
public static void main(String args[]){
ServerSocket server = null;
int port = 1234;
try{
System.out.println(“Attempting to bind a TCP port “ + port);
server = new ServerSocket(port);
}catch(SecurityException se){
System.out.println(“Trouble : ” + se.getMessage());
}catch(IOException ioe) {
System.out.println(“Trouble : ” + ioe.getMessage());
}
try{
Socket socket = server.accept();
System.out.println(“Accepting connection from: “ +
Socket.getInetAddress.getHostName());
socket.close();
}catch(SecurityException se){
System.out.println(“Trouble : ” + se.getMessage());
}catch(IOException ioe){
System.out.println(“Trouble : ” + ioe.getMessage());
}
}
}

Getting Server Socket Information


Server socket objects have two identifying attributes: the port number and the InetAddress they are
bound to. The java.net.ServerSocket class provides methods to query two values. The get
InetAddress() method returns the IP address of the interface to which the server socket is bound. The
simple server socket constructor binds the server socket to the requested port on all available
interfaces. In such cases, the get InetAddress() method returns the special IP address 0.0.0.0 which
should be interpreted as wild card (bound to all IP address).
Obtaining the port the server socket is bound to involve a simple invocation of the get Local Port ().
Inet Address get Inet Address ();
int get Local Port ();
Terminating Server Socket
A server socket may be terminated simply by invoking the no – argument close () method. Closing
the server socket will not affect connections that have already been returned by an accept ()
invocation. If the accept () method is invoked on a closed socket then a java.net.Socket Exception
will be thrown with a message indicating that the socket has been closed. The signature is as
follows–

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

void close() throws IO Exception;


Example code illustrating the server side of the Echo Client
The example program implements a server, Echo Server that accepts connection from the
EchoClient, which was implemented by the program EchoClient.java. The EchoServer simply
receives data from the client and echoes it back to Echo Client.
The server program is implemented by class Echo Server which contains main method for the server
program and performs the work of listening to the port establishing connections.
//EchoServer.java
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String args[]) {
Socket clientSocket;
ServerSocket serverSocket;
int port = 4444;
try {
serverSocket = new ServerSocket(port);
}catch(SecurityException se) {
System.out.println(“Trouble : ” + se.getMessage());
}catch(IOException ioe) {
System.out.println(“Trouble : ” + ioe.getMessage());
}
try{
clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
BufferedReader in = new BufferedReader(DataInputStream(System.in()));
String inputLine;
boolean finished = true;
do{
inputLine = in.ReadLine();
if(inputLine.equalsIgnoreCase(“quit”))
finished = true;
out.println(“Received : “ + inputLine());
out.flush();
}while(!finished);
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch(SecurityException se){
System.out.println(“Trouble : ” + se.getMessage());
}catch(IOException ioe) {
System.out.println(“Trouble : ” + ioe.getMessage());
}
}
}

Echo Server listens to its client Echo Client. It receives data being Echo Client and send it back to
the client as it is.
The server program begins by creating a new Server Socket object to listen on a specific port. The
port number used in this case is 4444.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

try{
serverSocket = new ServerSocket(port);
}catch(SecurityException se){
System.out.println(“Trouble : ” + se.getMessage());
}catch(IOException ioe){
System.out.println(“Trouble : ” + ioe.getMessage());
}
Server Socket is a java.net.class that provides a system independent implementation of the server
side of a client – server socket connection. The constructor of Server Socket throws an exception if it
can’t listen on the specified port. (for example, the port is already being used. In this case, the Echo
Server has to exit.
If the server successfully connects to its port, then the Server Socket object is successfully created
and the server continues to the next step – accepting a connection from a client.
try{
clientSocket = serverSocket.accept();
} catch(SecurityException se){
System.out.println(“Trouble : ” + se.getMessage());
} catch(IOException ioe){
System.out.println(“Trouble : ” + ioe.getMessage());
}
The accept() method waits until a client starts up and requests a connection on the host and port of
server. When a connection is requested and successfully established, the accept method returns a
new socket object which is bound to a new port. The server can communicate with the client over
this new socket and continue to listen for client connection requests on the Server Socket bound to
the original, predetermined port.
After the server successfully establishes a connection with a client, it communicates with the client
using this code:
PrintWriter out = new Print Writer (client Socket.get out put stream() );
BufferedReader in = new BufferedReader(new InputstreamReader(clientSocket.getInputStream());

The first statement here gets the client socket’s output stream and opens Print Writer on it. Similarly
in the next statement gets the client Socket’s input stream and opens a Buffered Reader on it.
String inputLine;
boolean finished = true;
do {
inputLine = in.ReadLine();
if(inputLine.equalsIgnoreCase(“quit”))
finished = true;
out.println(“Received : “ + inputLine());
out.flush();
}while(!finished);
To send data through the socket to the client Echo Server simply needs to write to the Print Writer.
To get the client’s response, Echo Server reads from the Buffered reader.
The next intensity part is do - while loop. The actual communication starts from this loop. The loop
reads a line at a time from the Input stream and immediately sends it to the client by writing it to the
Print Writer.
The do - while loop continues until the client sends “quit” to it. The do – while loop terminates and
the program continues to execute next lines of code:

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

in.close ();
out.close ();
client.Socket.close ();
server Socket.close ();
first two statement close the readers and writers connected to the socket. Next two statements close
the socket connections of client and server.

JAVA UDP PROGRAMMING


User Data Protocol
The Internet Protocol (IP) provides an unreliable, best effort datagram service. A datagram is an
independent self – contained message sent over the network, whose arrival, arrival time, and content
are not guaranteed. The second major IP transport layer protocol called the User Datagram
Protocol is responsible for datagram transport over a network. UDP is implemented as a very thin
layer on top of IP providing application port addressing, and datagram payload integrity verification.
Applications using UDP has lack of control in TCP streaming for the increased control, but also add
complexity in dealing with lost datagrams to single or multiple destinations.
An IP datagram originates in an Internet host and may contain up to 65516 bytes of payload data.
The IP datagram sent by the Internet host is then forwarded (routed) toward its destination over a
network of devices called routed. Each IP datagram begins with a fixed header storing the IP address
of the sender and the recipient, a checksum used to verify integrity of the header in case of data
corruption during transmission, and additional information used in making during decisions.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

UDP is very thin layer on top of IP, providing three additional functions –
 Destination Port Addressing – UDP datagram are marked with a destination port address,
this is in addition to the destination IP address. When a UDP/IP datagram is delivered to its
destination address, the protocol stack consults the UDP destination port value to decide
application should receive this datagram. UDP port numbers are 16 – bit port integer values
in range of 0 – 65535.
Although both the UDP and TCP protocols empty ports in the same range as a common de –
multiplexing mechanism, their actual use is independent of one another. It is perfectly
permissible for the same port number to be used by a TCP application and a UDP
application, or by other protocol for that matter. This is possible because the IP protocol
performs an initial de – multiplexing based on protocol type, so UDP and TCP packets are
separately identified and treated.
 Data Payload Integrity Verification – UDP associates a 16 – bit checksum with each
datagram sent. A checksum is a summary of the datagram contents computed using an
algorithm agreed upon between the sender and the receiver. Before transmitting the UDP
datagram, the sender computes this checksum summary and stores it in the UDP header.
Upon delivery, the recipient also independently computes the checksum for the datagram and
then compares it to the checksum stored in the UDP header. If they are the same, the
datagram integrity is considered verified.
Because a checksum is only a summary, different messages may have the same checksum
value. The trick is to select a checksum computation algorithm that catches the most likely
errors. UDP employs an algorithm called One’s complement that catches all single bit –
errors and many multiple – bit errors (odd – number errors are more likely to be detected). In
principle, it is possible that a datagram may be corrupted in a manner that does not affect its
checksum, but this is extremely unlikely in practice because datagrams are rarely corrupted
and when they are, they are typically 1 – bit errors.
 Source Port Identification – UDP stores the port number of the datagram socket used to
transmit a datagram. In combination with the IP header’s source IP address, they provide a
return address for UDP datagram receivers. IP and UDP are connections less protocols and
therefore when a datagram is delivered there is no backward channel to send response to. The
solution is to store the sender’s address and port in each UDP datagram to provide a unique
return address.
IP Fragmentation
A UDP datagram consists of the IP header (minimum 20 – bytes maximum 60 – bytes), and a fixed
length UDP header (8 bytes), followed by the payload data.
Both IP and UDP headers maintain packet length as a 16-bit value, therefore the largest UDP data
payload can be (216 –20 – 8) = 65508 bytes. However, most link layer protocols do not support such
large packet sizes. Link protocols typically have their own Maximum Transfer Unit (MTU). The
MTU specifies the largest frame (link-layer packet) that can be transmitted over a specified link
technology; for example, Ethernet frames can carry up to 1500 bytes of data. When an IP router
needs to transmit an IP packet that exceeds the MTU of the next-hop link; it may either drop the
packet, or perform IP fragmentation. In IP fragmentation, a single IP datagram is broken into
multiple, smaller IP datagrams that are re-assembled at the destination.
After the fragmentation all fragments are delivered using different possible routes. The fragmented
packets will be reassembled at the destination. As separate IP packets, fragments may arrive at the
destination out of order, and some may even be lost. If any fragment is lost, then the destination will
be unable to reassemble the original IP datagram so will drop it.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

Differences between UDP and TCP


When designing a network application, a choice must be made on the transport protocol that will be
used. There are many differences between the uses of UDP and the TCP protocol.
The main functions of TCP protocol are –
 Packet Ordering – TCP delivers IP packets in the order transmitted, through sequencing.
 Reliable Transmission – Lost packets are detected and recovered through retransmission.
 Streaming Abstraction – The TCP protocol can support the abstraction of a continuous bi –
directional communications byte – stream between two entities because data packets are
delivered reliably and in the order transmitted.
 Flow – control – The receiver can slow down the server if data is received at a rate that
exceeds the receiver’s processing capacity.
 Congestion control – TCP implements a distributed congestion control algorithm that slows
down individual stream transmission if packet loss is detected. The algorithm is tuned to
provide fair sharing of network resources among TCP streams. TCP provides a useful service
to application that need to exchange relatively large amounts of data in a reliable manner and
without real – time delivery constraints. On the other hand, the UDP protocol provides a less
reliable, packet – based service without support for flow or congestion control. It is there fore
suitable for application fitting different criteria –
 Small request and replies – If the client’s request and the server reply require less than 508
bytes, then they can be certainly fitted into a single UDP datagram. In such cases, the TCP
connection handshake and server state setup overheads become disproportionate.
 Read – only/re – entrant servers – When a UDP client does not receive a response to a
request; it cannot determine whether the request or response datagram was lost. If the request
did not modify server state, or did so in a way that resending the request would have the
same effect then the response loss can simply be handled through retransmission. Otherwise,
if the number of times a request is processed is important, the application must support more
complicated status check functionality.
 Stateless servers – If the protocol server does not need to maintain per – connection state,
then requests can be more easily split into multiple independent UDP datagram operations.
 Real – time Streaming – Multimedia applications playing live content need to stream data
over the Internet. It may appear that the TCP model is better fit for streaming application
requirements due to its streaming abstractions, loss recovery through retransmission, as well
as, flow and congestion control. The problem with TCP, however, is that it does not provide
applications with control over its functions. For example, if a packet is lost it only makes to
request retransmission if the round – trip latency is smaller than the time in which it will need
to be played. Additionally, if a part of the stream (in a packet) has not been received in times,
the application may want to skip part of the stream and keep reading from what is available.
Finally the application may need to receive flow and congestion notification, in order to
adjust its transmission quality.
For these reasons, many real – time applications do not use the TCP protocol. Lacking an
alternative, many such applications have built proprietary protocols over UDP.
Java UDP Programming
The Java language supports UDP network programming through java.net package. The java.net
package contains two classes to help to write Java programs that use datagrams to send and receive
packets over the network – Datagram Socket, Datagram Packet and Multicast Socket. Unlike

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

TCP sockets, no differentiation exists between server and client UDP sockets. Every datagram
Socket can be used both for sending, as well as, receiving datagram packets. The reason for
difference is that stream sockets are associated with a single stream, while datagram sockets do not
support a streaming abstraction and can be used to send and receive to and from multiple
destinations. Datagram Packets can be broadcast to multiple recipients all, listening to a Multicast
Socket.
In place of the java.io stream classes, Java datagram sockets use instances of the Datagram Packet
class. Datagram Packet instances are used to standard mail envelopes, containing a destination or
source address as well as a message of certain maximum size. Datagram Packet instances may only
be used with Datagram Socket instances, and cannot be used with TCP java.net.Socket instances.
The diagram illustrates the typical use of the Datagram Socket and Datagram Packet classes –
[2] Create
DatagramPacket
[5] Create
Java Java (buffer)
DatagramPacket
Client (“server”,4567,data) Server
Program Program

java.net java.net
Datagram [1] Create Datagram
Packet (4567) Packet
[4] Create
(any)
[6] send [3] receive
(datagram) (datagram)
UDP
Desti-
java.n

java.n
Datag

Datag
ocket

ocket
ramS

ramS

(sourc
et.

et.
nation
data e
port) [8] write
port)
sender
Host/port
[7] Create UDP Header + data
send as IP packet

Figure: Use of DatagramPacket and DatagramSocket classes

1. The java UDP server creates a Datagram Socket instance bound to a UDP port (specific
or arbitrarily chosen).
2. The server creates a Datagram Packet instance that will be used to store the next
datagram received.
3. The server than invokes the blocking Datagra Socket receive () method, passing the
datagram created.
4. The java UDP client creates a Datagram Socket instance, typically not bound to a
particular port.
5. The client next creates a Datagram Packet marked for delivery to the server’s address
and port, with the application – determined payload.
6. The datagram is then transmitted using the Datagram Socket’s send () method.
7. The header is created in transmission.
8. If the network manages to transmit the UDP packet to the other end (server) without
corrupting the headers or the payload, the data will be copied into the server’s Datagram
Packet instance and returned by unblocking the receive () call. If a receive () call has not

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

been made by the application the Datagram Packet instance will be buffered until it is
retrieved by the application. The checksum verification is performed by the system’s
UDP implementation and application can assume that delivered Datagram Packet
instances do not contain corrupted data.
java.net.DatagramPacket
The java.net.DatagramPacket class stores the header and data content of a UDP datagram.
Instances are used in sending as well as receiving UDP datagrams.
The three main attributes of the Datagram Packet class are –
 IP address
 UDP port
 The payload data stored in a byte – array.
When Datagram Packet instances are used for UDP transmission, the IP address and ports specify
the destination. When used for receiving UDP datagrams, they specify the source IP address and
port.
Constructors
There are four ways to construct a DatagramPacket instance. The first two constructors are typically
used when reading UDP datagrams, the other two ways are typically used when transmitting UDP
datagrams. These uses are characterized as typical because the class provides update method
allowing programmers to supply missing arguments after construction. Construction can be defined
in following ways –
 DatagramPacket (byte [] buf,int length)
This is the simplest constructor, which creates a DatagramPacket instance that uses the byte
array argument as buffer, and the integer argument as the maximum buffer length to be used.
An Illegal Argument Exception will be thrown if the buffer size of the array provided at
constructor execution time is smaller than the specified length.
The constructor, and in fact every DatagramPacket method, does not throw an I/O exception
since it does not perform any communication in itself. Communication only occurs through
java.net.DatagramSocket method invocations. If the application cannot predict the buffer size
it accepts to receive it should provide the maximum UDP size of 65508 bytes.
 DatagramPacket (byte [] buff, int offset, int length)
This second constructor adds support for offsetting writes to the byte buffer. In the previous
constructor, the DatagramPacket created used data stored in buffer indices [0…..length – 1].
In this constructor, the instance created will use indices [offset……offset + length – 1]. This
behavior may be appropriate in applications that want to append the data received into an
array containing other data, or want to send part of the data stored in an array. An illegal
Argument Exception will be thrown if the buffer size is smaller than (offset + length).
 DatagramPacket (byte [] buf, int length, Inet Address address, int port)
This constructor also accepts the byte array, length but also supports specification of the
packet’s destination address and port. The destination address and port are only used when
sending the packet using the java.net.DatagramPacket send () method. It is also possible to
use Datagram Packet instances to rreceive UDP datagrams in which case the address and port
values are overridden with the sender’s address and port. An Illegal Argument Exception
will be thrown if the buffer size is smaller than the specified length. No IO Exceptions are
thrown because the class does not perform any communications.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

 Datagram Packet (byte [] buf, offset, int length Inet Address address, int port)
This fourth constructor adds support for offsetting writes to the byte buffer to the third
constructor. In this constructor, the instance created will use indices [offset + length – 1].
This can be used to append the data received into an array containing other data.
Methods
The Datagram Packet class sup0ports read operations for accessing its three basic attributes
d: address, port, and data buffer (including buffer offset and length). No Exceptions are
thrown because the methods operate on local data.
 Inet Address get Address () –
The get Address () method returns destination or source address for this packet.
 Int get Port () –
The get Port () method returns the destination or source port number. It is up to the
application to remember if this packet has been constructed or received, in order to treat the
address and port number values accordingly. These methods get Address() and getPort() are
typically invoked on received datagrams in order to determine where the reply should be
sent.
Three methods are provided to access the Datagram Packet payload –
Byte[] getData ()
int getOffset ()
int getLength ()
The get Data () method returns the actual buffer, while the get offset () and get Length ()
methods return the range of buffer indices containing payload data.
The get Length () does not return the length specified in the constructor, but the actual length
of the data received of these methods, the get Length () is most commonly used to determine
how much data was received. If no offset has been specified, the get Offset () method returns
zero. In addition to the above read operations, DatagramPacket provides nearly equivalent
write methods.
 Void set Address (Inet Address ) – This method may be used to change the destination of
the packet.
 Void set Port (int Port ) – This method may be used to change the destination port of the
packet.
The Datagram Packet does not effect any communications, so setting the destination address
and port will only change behavior once the java.net.DatagramSocket send (Datagram Packet
method is invoked with the changed object as its argument.
It is possible to change the data buffer of the Datagram Packet by invoking one of the two set
Data () methods.
 Void set Data (byte [] buf ) – This method takes as argument a byte array that will
henceforth be used as the Packet’s data storage. Unlike the constructor, this method does not
require a length argument. The method specification states that the previously set length will
be used, unless it is greater than the new buffer length, in which case the buffer length is
used. If the intended use of the set Data (byte[] ) method invocation was to also reset the
length to the size of the new buffer, then a separate call to set Length () method must be
made.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

The set Length () methods permits users to change the number of bytes from the byte array
buffer that are considered to hold valid data. If the length specified exceeds the current
buffer’s length, an Illegal Argument Exception will be thrown.
 Void set data(byte [ ] buf, int offset, int length) – This method takes a byte array buffer, an
integer offset and an integer length as arguments and sets the datagram’s payload as
described in the constructor, an invalid offset (less than zero, or greater length), or invalid
length (offset + length > buffer, size) will throw illegal argument exception. This second data
( ) method permits users to move the window on an exciting buffer by passing the same byte
array with a different offset and potentiality with a different length.

java.net.DatagramSocket
Instances of the java.net.DataagramSocket class can serve both as client as well as server datagram
sockets. By default, such instances encapsulate VDP sockets, although in principle this behavior
could be changed by invoking set DatagramSocketImplfactory().
Unlike stream sockets, datagram sockets do not have a protocol peer, therefore, the same socket
instance maybe used to send datagrams to any host /port destination as well as receive datagrams
from any host/post source.
Constructors
Because every DatagramSocket instance can be used to receive datagrams it must be associated with
a unique UDP port on the local host. To simplify use when the specific port number assigned is not
important, a non-argument constructor has been provided, whose behavior is to pick an available
UDP port (known as an ephemeral port).
A java.net.SocketException may be thrown at construction time if no free port is available, or due to
some underlying operating system failure. In addition, a runtime SecurityException may be thrown
if the “listen” permission has not been granted. Network permissions are protocol independent.
DatagramSocket() throws SocketException, SecurityException. The other two DatagramSocket
constructors permit users to specify port and optionally the particular interface used for binding.
Both constructors may throw a SocketException if the port is in use, or could not be assigned due to
some operating system failure. Similar to the no-argument constructor, the runtime
SecurityException may be thrown if the “listen” socket permission has not been granted. An
additional error condition may occur in the second constructor if an IP address that does not belong
to the local host is provided. A SocketException is also used to signal this error.
DatagramSocket(int port) throws SocketException,
SecurityException;
DatagramSocket(int port,InetAddress address) throws
SocketException, SecurityException;
Operations
The main role of the DatagramSocket is to send and receive datagrams. Datagrams may be sent by
invoking the send() method with a DatagramPacket instance. The destination host and port can not
be specified in the send() method invocation, therefore they must be set in the DatagramPacket. This
can be achieved by either passing the destination address and port during DatagramPacket instanced
construction, or invoking the DatagramPacket setAddress() and setPort(0 methods.
void send(DatagramPacket packet) throws
IOException,SecurityException, IllegalargumentException;

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

Invocations may fail for a number of reasons –


 Sun’s JDK 1.3/1.4 implementations throw a runtime NullPointerException if the packet’s
address and port attributes have not been configured, as the send() method will not know
where to forward it to.
 An IOException may be thrown if the packet could not be successfully transmitted by the
system, if the socket has been closed, or if the packet exceeds the maximum size supported
by the system.
 A runtime SecurityException may be thrown if “connect” SocketPermission has not been
granted for the target address and port.
 An IllegalArgumentException may be thrown if the Socket has been restricted to a single
destination through a connect() call, and the packet address and port do not match the
configured destination address and port.
Datagrams may be received by invoking the blocking receive() method. The receive() method does
not return a result, instead it operates by side-effect.
void receive(DatagramPacket packet) throws IOException,
SecutiryException;
Invocations requires a DatagramPacket instance as an argument that will be used to store the next
datagram received. Any data previously held in the DatagramPacket instance will be overwritten.
The method may throw an IOException if the socket has been closed, or a communication error
occurs. The runtime SecurityException may also be thrown if the “accept” socketPermission has not
been granted to the host and port that sent blocks until a datagram is received, or the socket is
setTimeout() method, a java.io.InterruptedException may be thrown to signal a timeout.
Because DatagramSocket instances tie up operating system resources, such as UDP ports and file
handles, it is necessary to explicitly close a datagram socket before the object is garbage collected.
Once the close() method has been invoked the send() and receive() operations will fail.
void close();
Methods
All DatagramSocket instances may be used for receiving datagrams, and therefore must be
associated with a UDP port and a network interface address may be user selected or system assigned.
int getLocalPort();
The getLocalPort() method returns the UDP port this datagram socket is bound to. Current
implementations return the port number even if the datagram socket has been closed, so users should
not depend on this method to check socket termination.
Inetaddress getLocalAddress()
The getLocalAddress() method returns the address of the interface used in binding. The default
DatagramSocket behavior is to bind to all interfaces represented by the special IP address 0.0.0.0.
Both methods do not throw an exception because they are not dependent on the state of the socket.
DatagramSocket may be used to send and receive from any Internet address/UDP port combination.
This behavior is due to the connectionless nature of the UDP protocol. In some cases, however, it
may be desirable to configure a DatagramSocket instance to send packets to a single destination
only.
There are two main advantages in coding the destination in the DatagramSocket as opposed to the
DatagramPacket. The first advantage is that the code producing the DatagramPacket instances does
not need to know the recipient. The second advantage is that the security check for the “connect”

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

socket permission only needs to be performed once, at the time the datagram socket is configured to
the destination.
The connect() method configures the socket to transmit datagrams only to the destination specified.
An IllegalArgumentException will be thrown if the address or port arguments are invalid. Invoking
connect() results in a security check for “connect” permission to the specified address and port. If the
security check fails, a SecurityException will be thrown.
void connect(InetAddress address,int port) throws SecurityException,
IllegalArgumentException;
DatagramSocket instances restricted to a single destination may be reverted to the default
unrestricted state by invoking the disconnect() method. It is safe to invoke disconnect() even if the
socket has not been configured using a connect invocation.
void disconnect()
Two methods are provided to query the restriction/connection state of a Datagram Socket.
The getInetAddress() method returns the destination address to which the datagram Socket has been
restricted, or null it if it is in the default unconnected state.
InetAddress getInetAddress();
Similarly, the getPort() method return the destination port to which the datagram socket has been
restricted or – 1 if the port is in default unconnected state.
int getPort();
Datagram Sockets share some common configuration attributes with stream sockets. The blocking
behavior of the receive() method may be controlled by invoking the setSoTimeOut() method.
void setSoTimeOut(int timeOut) throws socket Exception;
int get so Time out () throws Socket Exception;
A non – zero argument configures the DatagramSocket receive() method to throw a
java.io.InterruptedException if a packet has not been received after the given number of
milliseconds. This method is particularly useful because datagrams may be lost and, therefore, the
application could block indefinitely to set a time out. A zero argument to setTimeout() reverts to the
default infinite blocking receive() behavior.
The Datagram Socket class provides method to query the protocol stack’s current send and receive
buffer size. UDP datagrams exceeding the getSendBufferSize() can still be sent, and datagrams
exceeding the getReceiveBufferSize () can still be received. The values only affect the number of
bytes copied at a time. Applications that can predict datagram packet sizes, can use the
setReceiveBufferSize() and setSendBufferSize(). Methods to assist the low – level protocol stack in
reading packets efficiently.
void setSendBufferSize(int Size) throws Socket Exception;
int getSendBufferSize() throws socket Exception;
void getSendBufferSize(int size) throws Socket Exception;
int getReceiveBufferSize() throws socket Exception;
Examples of simple
Examples of Simple UDP Client - Server Application
//Server Program
//TimeServer.java

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

import java.net.*;
import java.io.*;
import java.util.*;

public class TimeServer


{
public static void main(String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket(2345);
String localAddress = InetAddress.getLocalHost().getHostName().trim();
int localPort = socket.getLocalPort();
System.out.println(localAddress + " : ");
System.out.println("The server is listening at " + localPort);
byte outBuffer[];
byte inBuffer[] = new byte[256];
DatagramPacket outDatagram;
DatagramPacket inDatagram = new DatagramPacket
(inBuffer,inBuffer.length);
boolean finish = false;

do
{
socket.receive(inDatagram);
InetAddress destAddress = inDatagram.getAddress();
String destHost = destAddress.getHostName().trim();
int destPort = inDatagram.getPort();
System.out.println("Received datagram from " + destHost +
" at port " + destPort);
String data = new String(inDatagram.getData()).trim();
System.out.println("It contained " + data);

if(data.equalsIgnoreCase("quit"))
finish = true;

String time = new Date().toString();

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

outBuffer = time.getBytes();
outDatagram = new
DatagramPacket(outBuffer,outBuffer.length,destAddress,destPort);
socket.send(outDatagram);
System.out.println("Send " + time + " to " + destHost +
" at port " + destPort);
}while(!finish);
}catch(IOException e){ }
}
}
//Client Program
//GetTime.java
import java.net.*;
import java.io.*;
import java.util.*;

public class GetTime


{
public static void main(String[] args)
{
try
{
DatagramSocket socket = new DatagramSocket();
InetAddress localAddress = InetAddress.getLocalHost();
String localHost = localAddress.getHostName();

byte outBuffer[];
byte inBuffer[] = new byte[256];

DatagramPacket outDatagram;
DatagramPacket inDatagram = new DatagramPacket
(inBuffer, inBuffer.length);

for(int i=0;i<5;i++)
{
outBuffer = new byte[256];
outBuffer = "time".getBytes();

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

outDatagram = new DatagramPacket


(outBuffer,outBuffer.length,localAddress,2345);
socket.send(outDatagram);
System.out.println("Send request to" + localHost + " at port 2345");

socket.receive(inDatagram);
InetAddress destAddress = inDatagram.getAddress();
String destHost = destAddress.getHostName().trim();
int destPort = inDatagram.getPort();
System.out.println("Received datagram from " + destHost +
" at port " + destPort);
String data = new String(inDatagram.getData());
data = data.trim();
System.out.println("It contained " + data);
System.out.println("\n\n\n");
}

outBuffer = new byte[256];


outBuffer = "quit".getBytes();
outDatagram = new DatagramPacket
(outBuffer,outBuffer.length,localAddress,2345);
socket.send(outDatagram);
}catch(IOException e){ }
}
}
UDP Chat Service – An Example
This example consists of two applications: a client and a server. The server & client receive the
datagram packets over a datagram socket. First datagram packet received by server indicates a
request for a chat. When the server receives a datagram, it replies by sending a datagram packet that
contains the reply. This chatting contains until client program desires and send “quit” terminating the
session. These applications are implemented using Applet programming.
The ChatServerApp Class
//ChatServerApp.java
import java.lang.*;
import java.util.*;
import java.io.*;
import java.applet.*;

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

import java.awt.*;
import java.awt.event.*;
import java.net.*;

/*<APPLET CODE=ChatServerApp.java HEIGHT=600 WIDTH=450>


</APPLET/> */

public class ChatServerApp extends Applet implements Runnable, ActionListener


{
Button send;
TextArea are;
Panel p1, p2;

Thread recThread;
boolean finished = false;
byte outBuffer[];
byte inBuffer[] = new byte[256];
DatagramSocket socket;
DatagramPacket outDatagram;
DatagramPacket inDatagram;
InetAddress destAddress;
String localAddress,data;
int localPort,destPort;
public void init()
{
p1 = new Panel();
p2 = new Panel();
send = new Button(“Go”);
area = new TextArea(20,50);
text = new TextField(25);
add(p1);
add(p2);
p1.add(text);
p1.add(send);
p2.add(area);
send.addActionListener(this);
recThread = new Thread(this);

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

try
{
socket = new DatagramSocket(2345);
localAddress = InetAddress.
getLocalHost().getHostName().trim();
localPort = socket.getLocalPort();
inDatagram = new DatagramPacket (inBuffer,inBuffer.length);
}
catch(IOException ex)
{
System.ou.println(“Trouble : “ + ex.getMessage());
}
}
public void start()
{
try
{
recThread.start();
}
catch(UninterruptedException ue)
{
System.ou.println(“Trouble : “ + ue.getMessage());
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
area.append(“\n SEND : “ + text.getText());
outBuffer = text.getText().getByte();
outDatagram = new DatagramPacket(outBuffer,
outBuffer.length,destAddress,destPort);
socket.send(outDatagram);
text.setText(“”);
}
catch(IOException ex1)
{

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

System.out.println(“Trouble : “ + ex1.getMessage());
}
}

public void run()


{
try
{
do
{
socket.receive(inDatagram);
destAddress = inDatagram.getAddress();
destPort = inDatagram.getPort();
data = new String
(inDatagram.getData()).trim();
if(data.equalsIgnoreCase(“quit”))
finished = true;
area.append(“\RECEIVE : “ + data);
}while(!finished);
}
catch(IOException ex2)
{
System.out.println(“Trouble : “ + ex2.getMessage());
}
}
public void stop()
{
socket.close();
recThread.stop();
}
}
The ChatServerApp class initially set the environment of Applet. Complete area of applet divided
into two panels. First panel contains text field to receive text and a button “Go” to send the desired
text to client. Second panel of the server’s applet contains a text area having 20 rows and 50
columns. The text area is defined to simply display the received and transported text.
The ChatServerApp class performs two main tasks first receive the data over socket and second send
the message over the same socket. For these tasks the server class creates a thread named recThread.
After that in the init method there is a try block –

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

try
{
socket = new DatagramSocket(2345);
localAddress = InetAddress.getLocalHost().getHostName().trim();
localPort = socket.getLocalPort();
inDatagram = new DatagramPacket(inBuffer,inBuffer.length);
}
catch(IOException ex)
{
System.ou.println(“Trouble : “ + ex.getMessage());
}
First statement creates a datagram socket socket which listens on port number 2345. Next two
statements are defined to get the environment Variables,that is, localPort number, localHost name
etc. to create the DatagramPacket. In the fourth statement datagram packet is inDatagram is created
using DatagramPacket’s constructor. In this constructor an array of bytes ou Buffer[] is used. The
Datagram Packet will be used to receive a datagram packet from the socket because of the
constructor used to create it. This constructor requires only two arguments: a byte array that contain
client – specific data and the length of the byte array.
After the init () method the thread recThread is started using the start () method of this
program –
try
{
recThread.start();
}
catch(UninterruptedException ue)
{
System.ou.println(“Trouble : “ + ue.getMessage());
}
Now the run method of the server class is as follows –
do
{
socket.receive(inDatagram);
destAddress = inDatagram.getAddress();
destPort = inDatagram.getPort();
data = new String(inDatagram.getData()).trim();
if(data.equalsIgnoreCase(“quit”))
finished = true;
area.append(“\RECEIVE : “ + data);
}while(!finished);

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

The run method overrides the run in a Thread class and provides the implementation for the thread
recThread. The run method contains a do – while loop that continues as long as until unless the
client program sends the message quit/QUIT/Quit etc.
During each iteration of the loop, the thread waits for a Datagram Packet to arrive over the Datagram
Socket. The packet indicates a message from a client. In response to the client’s message, the Chat
Server App reads a message in a text field from the user and puts it in datagram and sends it over a
socket.
The first statement receives a datagram from the socket (the information received from the client
gets copied into the packet). The receive method waits forever until a packet is received. If no packet
is received, the server makes no further progress and just wits when it received a packet, it reads the
InetAddress and the port number of the packet from its header which is implemented in the next two
statement of the run method. It checks the data whether it is “quit” or not. If it is, and then it
terminates the do – while loop otherwise the message is appended to the text area.
Another main task which is performed by Chat Server App class is send responses the client. This
task is implemented in the action performed method of the server program. It contains following
code –
try
{
area.append(“\n SEND : “ + text.getText());
outBuffer = text.getText().getByte();
outDatagram = new DatagramPacket(outBuffer,
outBuffer.length,destAddress,destPort);
socket.send(outDatagram);
text.setText(“”);
}
In the response to the received message the user can input his message in the text field. After editing
the text field the button Go should be passed. When the button is pressed the relative event is fired
which is implemented with in the action Performed method which overrides the action Performed
method of the java.awt.event class.
The first statement simply appends the text in the text area which ever is being edited in the text
field.
The second statement reads the text field’s text in the bytes form. The next statement creates a new
Datagram Packet object intended for sending a datagram message over the datagram Socket. This
constructor requires four arguments. The first two arguments are the same required by the
constructor used to create receiving datagrams : a byte array “out Buffer”, containing the message
from the sender to the receiver and the length of this array. The next two arguments are different : an
Internet address and a port numbger. These two arguments are the complete address of the
destination of the datagram Packet and must be supplied by the sender of the datagram. These two
argument were read previously from the received datagram packet in the run ()method. The next line
of code sends the Datagram Packet on its way. The last line simply clears the text field.
Finally the stop method of the Chat Server App class –
socket.close();
recThread.stop();

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

First statement closes the Datagram socket connection next statement stops the running Thread – rec
Thread.
These lines of code fall into category the of house keeping because a well behaved program must
always cleans up after itself. All the resources used by the program must kept free after the
execution. Therefore all the sockets, streams, Thread must be closed or stop.
The ChatClientApp class
The chat client App class implements a client application for the chat server – App class. This
application sends request to the serve, waits for response and when the response is received,
communication starts. The code is as following –
//ChatClientApp.java
import java.lang.*;
import java.util.*;
import java.io.*;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
/*<APPLET CODE=ChatClientApp.java HEIGHT=600 WIDTH=450></APPLET/> */

public class ChatClientApp extends Applet implements Runnable, ActionListener{


Button send;
TextArea are;
Panel p1, p2;
int i;
Thread recThread;
boolean finished = false;
byte outBuffer[];
byte inBuffer[] = new byte[256];
DatagramSocket socket;
DatagramPacket outDatagram;
DatagramPacket inDatagram;
InetAddress localAddress;
String data;
String firstMessage;

public void init(){


p1 = new Panel();
p2 = new Panel();
send = new Button(“Go”);
area = new TextArea(20,50);
text = new TextField(25);
add(p1);
add(p2);
p1.add(text);
p1.add(send);
p2.add(area);
send.addActionListener(this);
recThread = new Thread(this);
try{
socket = new DatagramSocket();
localAddress = InetAddress.getLocalHost();

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

inDatagram = new DatagramPacket (inBuffer,inBuffer.length);


}
catch(IOException ex){
System.ou.println(“Trouble : “ + ex.getMessage());
}
}
public void start(){
try{
recThread.start();
}catch(UninterruptedException ue){
System.ou.println(“Trouble : “ + ue.getMessage());
}
}
public void actionPerformed(ActionEvent ae){
try{
outBuffer = new byte[256];
outBuffer = null;
if(i != 5)
outBuffer = text.getText().getByte();
else
outBuffer = “quit”.getBytes();
outDatagram = new DatagramPacket(outBuffer,
outBuffer.length,localAddress,2345);
socket.send(outDatagram);
text.setText(“”);
}catch(IOException ex1){
System.out.println(“Trouble : “ + ex1.getMessage());
}
}
public void run(){
try{
outBuffer = new byte[256];
firstMessage = ”Hello . . . Sapna calling”;
outBuffer = firstMessage.getBytes();
outDatagram = new DatagramPacket(outBuffer,
outBuffer.length,localAddress,2345);
socket.send(outDatagram);
area.append(“SEND:” + firstMessage);
for(int i=0;i<=5;i++){
socket.receive(inDatagram);
data = new String(inDatagram.getData()).trim();
area.append(“\RECEIVE : “ + data);
}
}catch(IOException ex2){
System.out.println(“Trouble : “ + ex2.getMessage());
}
}
public void stop(){
socket.close();
recThread.stop();
}
}

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

The ChatClientApp initially set the Applet environment, to use it in web programs. The top portion
of the program declares several local variables for its use. Area of the applet of chat client App is
also divided into two main parts i.e. panels – panel 1 and panel 2. First panel contains the
components to interaction which are send buttons and the text field having size of 25. When user
wants to send some message to the server, he has to type the message in the text field and then click
on the button. Second panel of the applet contain a text area component having 20 rows and 50
columns. This area is used to display the sent and received text.
Like ChatServerApp. Class, ChatClientApp class also performs two main tasks. First send the text
over a socket and receive the packet from the server.
Next, the init method creates a Datagram Socket:
Socket = new Datagram Socket () ;
The client uses a constructor that does not require a port number. This constructor just binds the
Datagram Socket to any available local port. It doesn’t matter what port the client is connected
because the Datagram Packet contain the address information. The server gets the port number from
the Datagram Packets and sends its response to that port.
The ChatClientApp performs two main tasks, for receiving client program creates a thread named
rec Thread. This is also initialized in the init() method.
After the init () method the rec Thread is started in the start () method.
Now the run () method of the client class is as follows –
try{
outBuffer = new byte[256];
firstMessage = ”Hello . . . Sapna calling”;
outBuffer = firstMessage.getBytes();
outDatagram = new DatagramPacket(outBuffer,
outBuffer.length,localAddress,2345);
socket.send(outDatagram);
area.append(“SEND:” + firstMessage);
for(int i=0;i<=5;i++){
socket.receive(inDatagram);
data = new String(inDatagram.getData()).trim();
area.append(“\RECEIVE : “ + data);
}
}catch(IOException ex2){
System.out.println(“Trouble : “ + ex2.getMessage());
}
The run method overrides the run in a Thread class and provides implementation for the rec Thread.
Previously, in the init () method code gets the Internet address for local host named –
localAddress = InetAddress.getLocalHost();
This InetAddress and the port number 23345 (the port number that the server used to create its
Datagram Socket) are then used to create datagram Packet destined for that InetAddress and port
number. Therefore the Datagram packet will be delivered to the chat server App. At start, the first
message is send to server from the client automatically to establish the connection and initiate the
communication.
The code creates a DatagramPacket with and empty byte array. Next, this method implements a for
– loop which executes for 5 times i.e. 0 – 4. This loop client gets a response from the aerver and
displays it in the text area.

Compiled By: Sapna Saxena (Goldie Compu Educations)


Java Network Programming

To get a response from the server, the client creates a inDatagram packet and used the Datagram –
socket receive method to receive the reply from the server. The receive method waits until a
datagram packet destined for the client comes through the socket. If the server’s reply is somehow
lost, the client will wait forever because of the no – guarantee policy of the datagram model.
When the client receives a reply from the server the client uses the get Data () method to retrieve that
data from the packet. The client then converts the data to a string and displays it in a text area.
Another main task performed by ChatClientApp is send responses to the server. This is implemented
in action Performed method. In the response to the received message the user can input his message
in the text field. After editing the text field the Go button should be pressed. When the button is
pressed the relative event is fired which is implemented in this method which overrides the action
performed method of the java.awt.event class action Performed method creates a new byte array.
Then creates a new datagram packet object intended to send message towards server. To send this
datagram Packet, InetAddress which was read previously in the program and the port number 2345
is used. The actual sending is cone through the send method of the Datagram socket class.
Running the Client & Server Programs
After editing these programs using appropriate editors, these programs should be compiled using
“java c” compiler of the JDK.
C: \javafiles\UDP\Chat> javac Chat Server App.java
C: \Javafiles\UDP\Chat> javac Chat Client App.java
After successful compilation of the program two HTML codes should be written to start the applets
from the web programs, or simply view them using applet viewer.
First, the program would be start using applet viewer like follows –
C: \Javafiles\UDP\chat> appletviewer chat server App.java
The applet will appear on the screen and wait for the socket connection from the client program. For
this program would be start from another host –
C: \Javafiles\UDP\chat>applet viewer Chat Client App.java
The client applet will be appear on the screen. In the server’s applet the first message will appear
sent by the client by the client program. Which would be –
Receive : Hello……….Sapna calling

Compiled By: Sapna Saxena (Goldie Compu Educations)

You might also like