KEMBAR78
TCP/IP Notes | PDF | Transmission Control Protocol | Internet Protocols
0% found this document useful (0 votes)
10 views49 pages

TCP/IP Notes

The document contains class notes for the Advance Java course (IT501E) at Government Polytechnic, Nagpur, authored by Sumit Ashok Khatri. It covers topics such as networking and socket programming, Java Database Connectivity (JDBC), and various components and architectures related to these subjects. The notes are structured with detailed sections and references for further study.

Uploaded by

Ayush Shahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views49 pages

TCP/IP Notes

The document contains class notes for the Advance Java course (IT501E) at Government Polytechnic, Nagpur, authored by Sumit Ashok Khatri. It covers topics such as networking and socket programming, Java Database Connectivity (JDBC), and various components and architectures related to these subjects. The notes are structured with detailed sections and references for further study.

Uploaded by

Ayush Shahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Government Polytechnic, Nagpur

Department of Computer Engineering

Class Notes for the course of Advance Java - IT501E

EVEN 2020

by

Sumit Ashok Khatri


M.Tech. (Computer Science) - Hyderabad Central University
Lecturer - Government Polytechnic, Nagpur
Former DevOps Engineer - Amazon Development Centre, Hyderabad
Contents

1 NETWORKING AND SOCKET PROGRAMMING 1


1.1 Overview of TCP/IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 TCP/IP Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2.1 Internet Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2.1.1 Class A Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1.2 Class B Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1.3 Class C Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Internet Addresses Using Zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 TCP/IP Internals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1 IP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.1.1 IP Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 The Transport Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.2.1 UDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.2.2 TCP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3.2.3 TCP Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.4 Network Programming Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.1 The Client/Server Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.4.2 Ports and Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.4.3 Connection-Oriented Versus Connectionless Communication . . . . . . . . . . . . . . . . . . 8
1.5 Starting Network Programming in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5.1 The java.net Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5.2 The InetAddress Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5.2.1 Factory Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.5.2.2 Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.3 Socket and ServerSocket class : TCP Client, TCP Server . . . . . . . . . . . . . . . . . . . 10
1.5.3.1 The Socket Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5.3.2 The ServerSocket Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5.3.3 TCP/IP Client - Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5.4 DatagramSocket and DatagramPacket class . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5.4.1 The DatagramSocket Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5.4.2 The DatagramPacket Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.5.4.3 Datagram (UDP/IP) Client-Server . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.5.5 The URL Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.5.5.1 Basics of URL Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.5.6 The URLConnection and HttpURLConnection Class . . . . . . . . . . . . . . . . . . . . . . 22
1.6 REFERENCES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

2 Java Database Connectivity 25


2.1 JDBC Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.2 JDBC Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.2.1 Two-tier and Three-tier Processing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.3 JDBC Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.4 JDBC Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.4.1 Type I: JDBC-ODBC Bridge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
2.4.2 Type II: Partial Java driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.4.3 Type III: Pure Java driver for database middleware . . . . . . . . . . . . . . . . . . . . . . 28
2.4.4 Type IV: Direct-to-database pure Java driver . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.4.5 Which Driver to use When? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

i
Advance Java Sumit A. Khatri

2.5 Security Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30


2.5.1 JDBC and untrusted applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.5.2 JDBC and Java applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.5.3 Network security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.5.4 Security Responsibilities of Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.6 Database connectivity using JDBC API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
2.6.1 Example 1: SQL SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.6.2 Example 2: SQL UPDATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.7 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3 REMOTE METHOD INVOCATION 34


3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.2 Serialization, Deserialization and Object Persistence in Java . . . . . . . . . . . . . . . . . . . . . . 34
3.3 Java Distributed Object Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3.1 Definition of Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3.2 The Distributed and Nondistributed Models Contrasted . . . . . . . . . . . . . . . . . . . . 37
3.3.3 RMI Interfaces and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.3.3.1 The Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.3.3.2 The RemoteException Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.3.3.3 The RemoteObject Class and its Subclasses . . . . . . . . . . . . . . . . . . . . . . 38
3.3.3.4 Implementing a Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.3.3.5 Locating Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.4 RMI Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.4.1 The Stub/Skeleton Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.4.2 The Remote Reference Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.4.3 The Transport Layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.5 Defining Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.6 Creating A Remote Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.6.1 Create a Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.6.2 Implement The Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.6.3 Run rmic on remote implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.6.4 Starting The Remote Registry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.6.5 Starting The Remote Service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
3.6.6 Creating A Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
3.7 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

CONTENTS ii
List of Figures

1.1 TCP/IP Protocol Suite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2


1.2 Class A Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Class B Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Class C Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Internet examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 IP Address Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Synchronizing Sequence Numbers for TCP Connection . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8 The Client/Server Model of Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.9 A Client-Server Transaction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2.1 Two-Tier Architecture for Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26


2.2 Three-Tier Architecture for Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
2.3 JDBC Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.1 Serialization and Deserialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35


3.2 Serialization and Deserialization in Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.3 RMI Interfaces and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.4 The RMI runtime architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
3.5 Relationships among remote object, stub, and skeleton classes . . . . . . . . . . . . . . . . . . . . . 43
3.6 Rsults of compiling and running RemoteClient class . . . . . . . . . . . . . . . . . . . . . . . . . . 45

iii
Chapter 1

NETWORKING AND SOCKET


PROGRAMMING

The term network programming refers to writing programs that execute across multiple devices (computers), in
which the devices are all connected to each other using a network. We know that Computers running on the
Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram
Protocol (UDP). The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide
the low-level communication details, allowing you to write programs that focus on solving the problem at hand.

1.1 Overview of TCP/IP


TCP/IP means Transmission Control Protocol and Internet Protocol. It is the network model used in the
current Internet architecture as well. Protocols are set of rules which govern every possible communication over
a network. These protocols describe the movement of data between the source and destination or the internet.
These protocols offer simple naming and addressing schemes. TCP/IP that is Transmission Control Protocol and
Internet Protocol was developed by Department of Defence’s Project Research Agency (ARPA, later DARPA) as
a part of a research project of network interconnection to connect remote machines.
The features that stood out during the research, which led to making the TCP/IP reference model were:
• Support for a flexible architecture. Adding more machines to a network was easy.

• The network was robust, and connections remained intact until the source and destination machines were
functioning.
The overall idea was to allow one application on one computer to talk to(send data packets) another application
running on different computer.

1.2 TCP/IP Addressing


TCP/IP includes an Internet addressing scheme that allows users and applications to identify a specific network
or host to communicate with. An Internet address works like a postal address, allowing data to be routed to
the chosen destination. TCP/IP provides standards for assigning addresses to networks, subnetworks, hosts, and
sockets, and for using special addresses for broadcasts and local loopback.
Internet addresses are made up of a network address and a host (or local) address. This two-part address
allows a sender to specify the network as well as a specific host on the network. A unique, official network address
is assigned to each network when it connects to other Internet networks. However, if a local network is not going
to connect to other Internet networks, it can be assigned any network address that is convenient for local use.
The Internet addressing scheme consists of Internet Protocol (IP) addresses and two special cases of IP
addresses: broadcast addresses and loopback addresses.

1.2.1 Internet Addresses


The Internet Protocol (IP) uses a 32-bit, two-part address field. The 32 bits are divided into four octets as in the
following:
01111101 00001101 01001001 00001111
These binary numbers translate into:

1
Advance Java Sumit A. Khatri

Figure 1.1: TCP/IP Protocol Suite

125 13 73 15
The two parts of an Internet address are the network address portion and the host address portion. This allows
a remote host to specify both the remote network and the host on the remote network when sending information.
By convention, a host number of 0 (zero) is used to refer to the network itself.
TCP/IP supports three classes of Internet addresses: Class A, Class B, and Class C. The different classes of
Internet addresses are designated by how the 32 bits of the address are allocated. The particular address class a
network is assigned depends on the size of the network.

1.2.1.1 Class A Addresses


The Class A address consists of an 8-bit network address and a 24-bit local or host address. The first bit in the
network address is dedicated to indicating the network class, leaving 7 bits for the actual network address. Since
the highest number that 7 bits can represent in binary is 128, there are 128 possible Class A network addresses.
Of the 128 possible network addresses, two are reserved for special cases: the network address 127 is reserved for
local loopback addresses, and a network address of all ones indicates a broadcast address.

Figure 1.2: Class A Address

Therefore, there are 126 possible Class A network addresses and 16,777,216 possible local host addresses. In
a Class A address (see Figure 1.2), the highest order bit is set to 0.
In other words, the first octet of a Class A address is in the range 1 to 126.

1.2.1.2 Class B Addresses


A Class B address consists of a 16-bit network address and a 16-bit local or host address. The first two bits in
the network address are dedicated to indicating the network class, leaving 14 bits for the actual network address.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 2


Advance Java Sumit A. Khatri

Figure 1.3: Class B Address

Therefore, there are 16,384 possible network addresses and 65,536 local host addresses. In a Class B address
(see Figure 1.3), the highest order bits are set to 1 and 0.
In other words, the first octet of a Class B address is in the range 128 to 191.

1.2.1.3 Class C Addresses


A Class C address consists of a 24-bit network address and an 8-bit local host address. The first two bits in the
network address are dedicated to indicating the network class, leaving 22 bits for the actual network address.

Figure 1.4: Class C Address

Therefore, there are 2,097,152 possible network addresses and 256 possible local host addresses. In a Class C
address (see Figure 1.4), the highest order bits are set to 1 and 1.
In other words, the first octet of a Class C address is in the range 192 to 223.

When deciding which network address class to use, you need to consider how many local hosts there will be
on the network and how many subnetworks there will be in the organization. If the organization is small and the
network will have fewer than 256 hosts, a Class C address is probably sufficient. If the organization is large, then
a Class B or Class A address may be more appropriate.

1.2.2 Internet Addresses Using Zeros


When a C class Internet address contains a 0 as the host address portion, (for example, 192.9.200.0), TCP/IP
sends a wild-card address on the network. This means that all machines with a Class C address of 192.9.200.X
(where X represents a value between 0 and 254) should respond to the request. This results in a network flooded
with requests to non-existent machines.
Similarly, problems occur for Class B addresses such as 129.5.0.0. All machines with a Class B address of
129.5.X.X. (where X represents a value between 0 and 254) are obliged to respond to the request. In this case, since
Class B addresses account for bigger networks than Class C addresses, the network is flooded with significantly
more requests to nonexistent machines than for a Class C network.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 3


Advance Java Sumit A. Khatri

1.3 TCP/IP Internals


The TCP/IP protocol suite is so named for two of its most important protocols: Transmission Control Protocol
(TCP) and Internet Protocol (IP). The main design goal of TCP/IP was to build an interconnection of networks,
referred to as an internetwork, or internet, that provided universal communication services over heterogeneous
physical networks. The clear benefit of such an internetwork is the enabling of communication between hosts on
different networks, perhaps separated by a large geographical area.
The Internet consists of the following groups of networks:
• Backbones: Large networks that exist primarily to interconnect other networks. Also known as network
access points (NAPs) or Internet Exchange Points (IXPs). Currently, the backbones consist of commercial
entities.
• Regional networks connecting, for example, universities and colleges.
• Commercial networks providing access to the backbones to subscribers, and networks owned by commercial
organizations for internal use that also have connections to the Internet.
• Local networks, such as campus-wide university networks.

Figure 1.5: Internet examples

Figure 1.5 shows two examples of internets. Each consists of two or more physical networks.

1.3.1 IP
IP provides communication between hosts on different kinds of networks (i.e., different data-link implementations
such as Ethenet and Token Ring). It is a connectionless, unreliable packet delivery service. Connectionless means
that there is no handshaking, each packet is independent of any other packet. It is unreliable because there is no
guarantee that a packet gets delivered; higher-level protocols must deal with that.
IP defines an addressing scheme that is independent of the underlying physical address (e.g, 48-bit MAC
address). IP specifies a unique 32-bit number for each host on a network. This number is known as the Internet
Protocol Address, the IP Address or the Internet Address. These terms are interchangeable. Each packet sent
across the internet contains the IP address of the source of the packet and the IP address of its destination.
For routing efficiency, the IP address is considered in two parts: the prefix which identifies the physical
network, and the suffix which identifies a computer on the network. A unique prefix is needed for each network in
an internet. For the global Internet, network numbers are obtained from Internet Service Providers (ISPs). ISPs
coordinate with a central organization called the Internet Assigned Number Authority (IANA).
The first four bits of an IP address determine the class of the network. The class specifies how many of the
remaining bits belong to the prefix (aka Network ID) and to the suffix (aka Host ID). The first three classes, A,
B and C, are the primary network classes. When interacting with mere humans, software uses dotted decimal
notation; each 8 bits is treated as an unsigned binary integer separated by periods. IP reserves host address 0 to
denote a network. 140.211.0.0 denotes the network that was assigned the class B prefix 140.211.

1.3.1.1 IP Routing
Each IP datagram travels from its source to its destination by means of routers. All hosts and routers on an
internet contain IP protocol software and use a routing table to determine where to send a packet next. The
destination IP address in the IP header contains the ultimate destination of the IP datagram, but it might go

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 4


Advance Java Sumit A. Khatri

Figure 1.6: IP Address Classes

through several other IP addresses (routers) before reaching that destination. Routing table entries are created
when TCP/IP initializes. The entries can be updated manually by a network administrator or automatically by
employing a routing protocol such as Routing Information Protocol(RIP). Routing table entries provide needed
information to each local host regarding how to communicate with remote networks and hosts.
When IP receives a packet from a higher-level protocol, like TCP or UDP, the routing table is searched for
the route that is the closest match to the destination IP address. The most specific to the least specific route is
in the following order:
• A route that matches the destination IP address (host route).
• A route that matches the network ID of the destination IP address (network route).
• The default route.
If a matching route is not found, IP discards the datagram.
IP provides several other services:
• Fragmentation: IP packets may be divided into smaller packets. This permits a large packet to travel
across a network which only accepts smaller packets. IP fragments and reassembles packets transparent to
the higher layers.
• Timeouts: Each IP packet has a Time To Live (TTL) field, that is decremented every time a packet moves
through a router. If TTL reaches zero, the packet is discarded.
• Options: IP allows a packet’s sender to set requirements on the path the packet takes through the network
(source route); the route taken by a packet may be traced (record route) and packets may be labeled with
security features.

1.3.2 The Transport Layer


There are two primary transport layer protocols: Transmission Control Protocol (TCP) and User Datagram
Protocol (UDP). They provide end-to-end communication services for applications.

1.3.2.1 UDP
This is a minimal service over IP, adding only optional checksumming of data and multiplexing by port number.
UDP is often used by applications that need multicast or broadcast delivery, services not offered by TCP. Like
IP, UDP is connectionless and works with datagrams.

1.3.2.2 TCP
TCP is a connection-oriented transport service; it provides end-to-end reliability, resequencing, and flow control.
TCP enables two hosts to establish a connection and exchange streams of data, which are treated in bytes.
The delivery of data in the proper order is guaranteed. TCP can detect errors or lost data and can trigger
retransmission until the data is received, complete and without errors.
A TCP connection is done with a 3-way handshake between a client and a server. The following is a simplified
explanation of this process.
• The client asks for a connection by sending a TCP segment with the SYN control bit set.
• The server responds with its own SYN segment that includes identifying information that was sent by the
client in the initial SYN segment.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 5


Advance Java Sumit A. Khatri

• The client acknowledges the servers SYN segment.


The connection is then established and is uniquely identified by a 4-tuple called a socket or socket pair:
(destination IP address, destination port number)
(source IP address, source port number)
During the connection setup phase, these values are entered in a table and saved for the duration of the connection.

1.3.2.3 TCP Header


Every TCP segment has a header. The header comprises all necessary information for reliable, complete delivery
of data. Among other things, such as IP addresses, the header contains the following fields:
1. Sequence Number - This 32-bit number contains either the sequence number of the first byte of data
in this particular segment or the Initial Sequence Number (ISN) that identifies the first byte of data that
will be sent for this particular connection. The ISN is sent during the connection setup phase by setting
the SYN control bit. An ISN is chosen by both client and server. The first byte of data sent by either
side will be identified by the sequence number ISN + 1 because the SYN control bit consumes a sequence
number. Figure 1.7 illustrates the threeway handshake. The sequence number is used to ensure the data is

Figure 1.7: Synchronizing Sequence Numbers for TCP Connection

reassembled in the proper order before being passed to an application protocol.


2. Acknowledgement Number - This 32-bit number is the other hosts sequence number + 1 of the last
successfully received byte of data. It is the sequence number of the next expected byte of data. This
field is only valid when the ACK control bit is set. Since sending an ACK costs nothing, (because it
and the Acknowledgement Number field are part of the header) the ACK control bit is always set after a
connection has been established. The Acknowledgement Number ensures that the TCP segment arrived at
its destination.
3. Control Bits - This 6-bit field comprises the following 1-bit flags (left to right):

• URG - Makes the Urgent Pointer field significant.


• ACK - Makes the Acknowledgement Number field significant.
• PSH - The Push Function causes TCP to promptly deliver data.
• RST - Reset the connection.
• SYN - Synchronize sequence numbers.
• FIN - No more data from sender, but can still receive data.
4. Window Size - This 16-bit number states how much data the receiving end of the TCP connection will
allow. The sending end of the TCP connection must stop and wait for an acknowledgement after it has sent
the amount of data allowed.

5. Checksum - This 16-bit number is the ones complement of the ones complement sum of all bytes in the
TCP header, any data that is in the segment and part of the IP packet. A checksum can only detect some
errors, not all, and cannot correct any.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 6


Advance Java Sumit A. Khatri

1.4 Network Programming Basics


Network applications are everywhere. Any time you browse the Web, send an email message, or pop up an X
window, you are using a network application. Interestingly, all network applications are based on the same basic
programming model, have similar overall logical structures, and rely on the same programming interface. Network
applications rely on many of the concepts that you have already learned in our study of systems. There are new
concepts to master as well. We will need to understand the basic clientserver programming model and how to
write client-server programs that use the services provided by the Internet.

1.4.1 The Client/Server Model


TCP is a peer-to-peer, connection-oriented protocol. There are no master/subordinate relationships. The appli-
cations, however, typically use a client/server model for communications, as demonstrated in Figure 1.8.

Figure 1.8: The Client/Server Model of Applications

A server is an application that offers a service to internet users. A client is a requester of a service. An
application consists of both a server and a client part, which can run on the same or on different systems. Users
usually invoke the client part of the application, which builds a request for a particular service and sends it to
the server part of the application using TCP/IP as a transport vehicle. The server is a program that receives
a request, performs the required service, and sends back the results in a reply. A server can usually deal with
multiple requests and multiple requesting clients at the same time.
Most servers wait for requests at a well-known port so that their clients know to which port (and in turn,
which application) they must direct their requests. The client typically uses an arbitrary port called an ephemeral
port for its communication. Clients that want to communicate with a server that does not use a well-known port
must have another mechanism for learning to which port they must address their requests. This mechanism might
employ a registration service such as portmap, which does use a well-known port.
Every network application is based on the client-server model. With this model, an application consists of a
server process and one or more client processes. A server manages some resource, and it provides some service for
its clients by manipulating that resource. For example, a Web server manages a set of disk files that it retrieves
and executes on behalf of clients. An FTP server manages a set of disk files that it stores and retrieves for clients.
Similarly, an email server manages a spool file that it reads and updates for clients. The fundamental operation
in the client-server model is the transaction (Figure 1.9). A client-server transaction consists of four steps:

Figure 1.9: A Client-Server Transaction.

1. When a client needs service, it initiates a transaction by sending a request to the server. For example, when
a Web browser needs a file, it sends a request to a Web server.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 7


Advance Java Sumit A. Khatri

2. The server receives the request, interprets it, and manipulates its resources in the appropriate way. For
example, when a Web server receives a request from a browser, it reads a disk file.
3. The server sends a response to the client, and then waits for the next request. For example, a Web server
sends the file back to a client.

4. The client receives the response and manipulates it. For example, after a Web browser receives a page from
the server, it displays it on the screen.
It is important to realize that clients and servers are processes and not machines, or hosts as they are often called
in this context. A single host can run many different clients and servers concurrently, and a client and server
transaction can be on the same or different hosts. The client-server model is the same, regardless of the mapping
of clients and servers to hosts.

1.4.2 Ports and Sockets


These entities lie at the heart of network communications. For anybody not already familiar with the use of
these terms in a network programming context, the two words very probably conjure up images of hardware
components. However, although they are closely associated with the hardware communication links between
computers within a network, ports and sockets are not themselves hardware elements, but abstract concepts that
allow the programmer to make use of those communication links.
A port is a logical connection to a computer (as opposed to a physical connection) and is identified by a
number in the range 1 to 65535. This number has no correspondence with the number of physical connections to
the computer, of which there may be only one (even though the number of ports used on that machine may be
much greater than this). Ports are implemented upon all computers attached to a network, but it is only those
machines that have server programs running on them for which the network programmer will refer explicitly to
port numbers. Each port may be dedicated to a particular server/service (though the number of available ports
will normally greatly exceed the number that is actually used). Port numbers in the range 1 to 1023 are normally
set aside for the use of specified standard services, often referred to as well-known services. For example, port 80
is normally used by Web servers.
For each port supplying a service, there is a server program waiting for any requests. All such programs run
together in parallel on the host machine. When a client attempts to make connection with a particular server
program, it supplies the port number of the associated service. The host machine examines the port number and
passes the clients transmission to the appropriate server program for processing.
In most applications, of course, there are likely to be multiple clients wanting the same service at the same
time. A common example of this requirement is that of multiple browsers (quite possibly thousands of them)
wanting Web pages from the same server. The server, of course, needs some way of distinguishing between clients
and keeping their dialogues separate from each other. This is achieved via the use of sockets . As stated earlier,
a socket is an abstract concept and not an element of computer hardware. It is used to indicate one of the
two end-points of a communication link between two processes. When a client wishes to make connection to a
server, it will create a socket at its end of the communication link. Upon receiving the clients initial request (on
a particular port number), the server will create a new socket at its end that will be dedicated to communication
with that particular client. Just as one hardware link to a server may be associated with many ports, so too may
one port be associated with many sockets.

1.4.3 Connection-Oriented Versus Connectionless Communication


Transport protocols are used to deliver information from one port to another and thereby enable communication
between application programs. They use either a connectionoriented or connectionless method of communication.
TCP is a connection-oriented protocol, and UDP is a connectionless transport protocol.
The TCP connection-oriented protocol establishes a communication link between a source port/IP address
and a destination port/IP address. The ports are bound together via this link until the connection is terminated
and the link is broken. An example of a connection-oriented protocol is a telephone conversation. A telephone
connection is established, communication takes place, and then the connection is terminated.
The reliability of the communication between the source and destination programs is ensured through error-
detection and error-correction mechanisms that are implemented within TCP. TCP implements the connection
as a stream of bytes from source to destination. This feature allows the use of the stream I/O classes provided
by java.io.
The UDP connectionless protocol differs from the TCP connection-oriented protocol in that it does not
establish a link for the duration of the connection. An example of a connectionless protocol is postal mail. To
mail something, you just write down a destination address (and an optional return address) on the envelope of the

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 8


Advance Java Sumit A. Khatri

item you’re sending and drop it into a mailbox. When using UDP, an application program writes the destination
port and IP address on a datagram and then sends the datagram to its destination. UDP is less reliable than TCP
because there are no delivery-assurance or error-detection-and-correction mechanisms built into the protocol.

1.5 Starting Network Programming in Java


1.5.1 The java.net Package
The java.net package provides several classes that support socket-based client/server communication.
The InetAddress class encapsulates Internet IP addresses and supports conversion between dotted decimal
addresses and host names.
The Socket, ServerSocket, DatagramSocket, and MulticastSocket classes implement client and server sockets
for connection-oriented and connectionless communication. The DatagramPacket class is used to construct UDP
datagram packets. The SocketImpl and DatagramSocketImpl classes and the SocketImplFactory interface provide
hooks for implementing custom sockets.
The URL, URLConnection, HttpURLConnection, and URLEncoder classes implement high-level browser-
server Web connections. The ContentHandler and URLStreamHandler classes are abstract classes that have
provided the basis for the implementation of Web content and stream handlers. They are supported by the
ContentHandlerFactory and URLStreamHandlerFactory interfaces.
The classes in the java.net package can be listed as follows:

The Classes
ContentHandler DatagramPacket DatagramSocket
DatagramSocketImpl HttpURLConnection InetAddress
MulticastSocket ServerSocket Socket
SocketImpl URL URLConnection
URLEncoder URLStreamHandler URI
Proxy HttpCookie ProxySelector
Interfaces
ContentHandlerFactory FileNameMap SocketOptions
SocketImplFactory URLStreamHandlerFactory CookiePolicy

1.5.2 The InetAddress Class


public class InetAddress
extends Object
implements Serializable
One of the classes within package java.net is called InetAddress , which handles Internet addresses both as host
names and as IP addresses. This class represents an Internet Protocol (IP) address. An IP address is either
a 32-bit or 128-bit unsigned number used by IP, a lower-level protocol on which protocols like UDP and TCP
are built. An instance of an InetAddress consists of an IP address and possibly its corresponding host name
(depending on whether it is constructed with a host name or whether it has already done reverse host name
resolution).

1.5.2.1 Factory Methods


The InetAddress has no visible constructors. To create an InteAddress object, you have to use one of the available
factory methods. Factory methods are merely a convention whereby static methods in a class return an instance
of that class. Three commonly used factory methods are listed:

• static InetAddress getLocalHost() throws UnknownHostException


Returns the Inetaddress object that represents the address of the local host.
• static InetAddress getByName(String hostName) throws UnknownHostException
Determines and returns the IP address (InetAddress) of a host, given the host’s name.
• static InetAddress[] getAllByName(String hostName) throws UnknownHostException
Given the name of a host, returns an array of its IP addresses (InetAddresses), based on the configured
name service on the system.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 9


Advance Java Sumit A. Khatri

1.5.2.2 Instance Methods


The InetAddress class has several other methods, which can be used on the objects returned by the methods just
discussed in 1.5.2.1. Here are some of the more commonly used methods:
• public boolean equals(Object other)
Compares this object against the specified object. The result is true if and only if the argument is not null
and it represents the same IP address as this object. Two instances of InetAddress represent the same IP
address if the length of the byte arrays returned by getAddress is the same for both, and each of the array
components is the same for the byte arrays.
• public byte[] getAddress()
Returns the raw IP address of this InetAddress object. The result is in network byte order: the highest
order byte of the address is in getAddress()[0].
• public String getHostAddress()
Returns the String that represents the host address associated with the InetAddress object.
• public String getHostName()
Returns the string that represents the host name associated with the InetAddress object.
• public boolean isMulticastAddress()
Return true if this address is a multicast address. Otherwise it returns false.
• public String toString()
Returns a string that lists the host name and the IP address for convenience.
The following program shows the use of some of the factory methods and instance methods of InetAddress class
1 // Demonstrate I n e t A d d r e s s .
2 im po rt j a v a . n e t . ∗ ;
3 c l a s s InetAddressTest
4 {
5 p u b l i c s t a t i c v o i d main ( S t r i n g a r g s [ ] ) throws UnknownHostException
6 {
7 I n e t A d d r e s s Address = I n e t A d d r e s s . g e t L o c a l H o s t ( ) ;
8 System . out . p r i n t l n ( Address . g e t H o s t A d d r e s s ( ) ) ;
9 System . out . p r i n t l n ( Address . getHostName ( ) ) ;
10
11 Address = I n e t A d d r e s s . getByName ( ” gpnagpur . ac . i n ” ) ;
12 System . out . p r i n t l n ( Address . g e t H o s t A d d r e s s ( ) ) ;
13 System . out . p r i n t l n ( Address . getHostName ( ) ) ;
14
15 I n e t A d d r e s s SW[ ] = I n e t A d d r e s s . getAllByName ( ”www. nba . com” ) ;
16 f o r ( i n t i = 0 ; i < SW. l e n g t h ; i ++)
17 {
18 System . out . p r i n t l n (SW[ i ] . g e t H o s t A d d r e s s ( ) ) ;
19 System . out . p r i n t l n (SW[ i ] . getHostName ( ) ) ;
20 }
21
22 }
23 }
Listing 1.1: InetAddress example

The output of above code is left as homework for you.

1.5.3 Socket and ServerSocket class : TCP Client, TCP Server


1.5.3.1 The Socket Class
The Socket class implements client connection-based sockets. These sockets are used to develop applications that
utilize services provided by connection-oriented server applications.
• Socket(String HostName, int port) throws UnknownHostException, IOException
constructor creates a socket connected to the named host and port.
• Socket(InetAddress ipAddress, int port) throws UnknownHostException, IOException
constructor creates a socket using preexisting InetAddress object and port.
The access methods of the Socket class are used to access the I/O streams and connection parameters associated
with a connected socket.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 10


Advance Java Sumit A. Khatri

• int getInetAddress() and int getPort()


methods get the IP address of the destination host and the destination host port number to which the
socket is connected.
• int getLocalPort()
method returns the source host local port number associated with the socket.
• getLocalAddress()
method returns the local IP address associated with the socket.
• InputStream getInputStream() throws IOException and OutputStream getOutputStream() throws IOExcep-
tion
methods are used to access the input and output streams associated with a socket.
• close()
method is used to close a socket.

1.5.3.2 The ServerSocket Class


The ServerSocket class implements a TCP server socket. It provides three constructors that specify the port to
which the server socket is to listen for incoming connection requests, an optional maximum connection request
queue length, and an optional Internet address. The Internet address argument allows multihomed hosts (that
is, hosts with more than one Internet address) to limit connections to a specific interface.

• ServerSocket(int port) throws IOException Constructor creates server socket on specified port with the
queue length of 50.
• ServerSocket(int port, int maxQueue) throws IOException Constructor creates server socket on specified
port with a maximum queue length of maxQueue.

• ServerSocket(int port,int maxQueue, InetAddress localAddress) throws IOException Constructor creates


server socket on specified port with a maximum queue length of maxQueue on a multihomed host, lo-
calAddress specifies the IP address to which this socket binds.
• accept() method is used to cause the server socket to listen and wait until an incoming connection is
established. It returns an object of class Socket once a connection is made. This Socket object is then used
to carry out a service for a single client.
• The getInetAddress() method returns the address of the host to which the socket is connected.
• The getLocalPort() method returns the port on which the server socket listens for an incoming connection.
• The toString() method returns the socket’s address and port number as a string in preparation for printing.

1.5.3.3 TCP/IP Client - Server


A communication link created via TCP/IP sockets is a connection-orientated link. This means that the connection
between server and client remains open throughout the duration of the dialogue between the two and is only broken
(under normal circumstances) when one end of the dialogue formally terminates the exchanges (via an agreed
protocol). Since there are two separate types of process involved (client and server), we shall examine them
separately, taking the server first. Setting up a server process requires five steps

1. Create a ServerSocket object.


The ServerSocket constructor requires a port number (1024 to 65535, for non- reserved ones) as an argu-
ment. For example:

ServerSocket serverSocket = new ServerSocket(1234);

In this example, the server will await (listen for) a connection from a client on port 1234.
2. Put the server into a waiting state.
The server waits indefinitely (blocks) for a client to connect. It does this by calling method accept of class
ServerSocket , which returns a Socket object when a connection is made. For example:

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 11


Advance Java Sumit A. Khatri

Socket link = serverSocket.accept();

3. Set up input and output streams.


Methods getInputStream and getOutputStream of class Socket are used to get references to streams asso-
ciated with the socket returned in step 2. These streams will be used for communication with the client
that has just made connection. For a non-GUI application, we can wrap a Scanner object around the
InputStream object returned by method getInputStream , in order to obtain string-orientated input (just
as we would do with input from the standard input stream, System.in ). For example:

Scanner input = new Scanner(link.getInputStream());

Similarly, we can wrap a PrintWriter object around the OutputStream object returned by method getOut-
putStream . Supplying the PrintWriter constructor with a second argument of true will cause the output
buffer to be fl ushed for every call of println (which is usually desirable). For example:

PrintWriter output = new PrintWriter(link.getOutputStream(),true);

4. Send and receive data.


Having set up our Scanner and PrintWriter objects, sending and receiving data is very straightforward. We
simply use method nextLine for receiving data and method println for sending data, just as we might do
for console I/O. For example:

output.println(”Awaiting data”);
String input = input.nextLine();

5. Close the connection (after completion of the dialogue). This is achieved via method close of class
Socket . For example:

link.close();

The following example program is used to illustrate the use of these steps.

In this simple example, the server will accept messages from the client and will keep count of those messages,
echoing back each (numbered) message. The main protocol for this service is that client and server must alternate
between sending and receiving (with the client initiating the process with its opening message, of course). The
only details that remain to be determined are the means of indicating when the dialogue is to cease and what
fi nal data (if any) should be sent by the server. For this simple example, the string ***CLOSE*** will be sent
by the client when it wishes to close down the connection. When the server receives this message, it will confi
rm the number of preceding messages received and then close its connection to this client. The client, of course,
must wait for the fi nal message from the server before closing the connection at its own end.
Since an IOException may be generated by any of the socket operations, one or more try blocks must be used.
Rather than have one large try block (with no variation in the error message produced and, consequently, no
indication of precisely what operation caused the problem), it is probably good practice to have the opening of
the port and the dialogue with the client in separate try blocks. It is also good practice to place the closing of
the socket in a fi nally clause, so that, whether an exception occurs or not, the socket will be closed (unless, of
course, the exception is generated when actually closing the socket, but there is nothing we can do about that).
Since the fi nally clause will need to know about the Socket object, we shall have to declare this object within a
scope that covers both the try block handling the dialogue and the fi nally block. Thus, step 2 shown above will
be broken up into separate declaration and assignment. In our example program, this will also mean that the
Socket object will have to be explicitly initialised to null (as it will not be a global variable).
Since a server offering a public service would keep running indefinitely, the call to method handleClient in our
example has been placed inside an infinite loop.
In the code that follows, port 1234 has been chosen for the service, but it could just as well have been any
integer in the range 102465535. Note that the lines of code corresponding to each of the above steps have been
clearly marked with emboldened comments.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 12


Advance Java Sumit A. Khatri

1 // S e r v e r t h a t e c h o e s back c l i e n t ’ s m e s s a g e s .
2 //At end o f d i a l o g u e , s e n d s message i n d i c a t i n g
3 // number o f m e s s a g e s r e c e i v e d . Uses TCP.
4 im po rt j a v a . i o . ∗ ;
5 im po rt j a v a . n e t . ∗ ;
6 im po rt j a v a . u t i l . ∗ ;
7 p u b l i c c l a s s TCPEchoServer
8 {
9 private s t a t i c ServerSocket serverSocket ;
10 p r i v a t e s t a t i c f i n a l i n t PORT = 1 2 3 4 ;
11 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
12 {
13 System . out . p r i n t l n ( ” Opening p o r t \n” ) ;
14 try
15 {
16 s e r v e r S o c k e t = new S e r v e r S o c k e t (PORT) ; // Step 1 .
17 }
18 c a t c h ( IOException ioEx )
19 {
20 System . out . p r i n t l n ( ” Unable t o a t t a c h t o p o r t ! ” ) ;
21 System . e x i t ( 1 ) ;
22 }
23 do
24 {
25 handleClient () ;
26 } while ( true ) ;
27 }
28 pri vate s t a t i c void handleClient ( )
29 {
30 S o c k e t l i n k = n u l l ; // Step 2 .
31 try
32 {
33 l i n k = s e r v e r S o c k e t . a c c e p t ( ) ; // Step 2 .
34 S c a n n e r i n p u t = new S c a n n e r ( l i n k . g e t I n p u t S t r e a m ( ) ) ; // Step 3 .
35 P r i n t W r i t e r ou tp ut =new P r i n t W r i t e r ( l i n k . getOutputStream ( ) , t r u e ) ; // Step 3 .
36 i n t numMessages = 0 ;
37 S t r i n g message = i n p u t . n e x t L i n e ( ) ; // Step 4 .
38 w h i l e ( ! message . e q u a l s ( ” ∗∗∗CLOSE∗∗∗ ” ) )
39 {
40 System . out . p r i n t l n ( ” Message r e c e i v e d . ” ) ;
41 numMessages++;
42 ou t put . p r i n t l n ( ” Message ” + numMessages+ ” : ” + message ) ; // Step 4 .
43 message = i n p u t . n e x t L i n e ( ) ;
44 }
45 ou tp ut . p r i n t l n ( numMessages+ ” m e s s a g e s r e c e i v e d . ” ) ; // Step 4 .
46 }
47 c a t c h ( IOException ioEx )
48 {
49 ioEx . p r i n t S t a c k T r a c e ( ) ;
50 }
51 finally
52 {
53 try
54 {
55 System . out . p r i n t l n ( ” \n∗ C l o s i n g c o n n e c t i o n ∗” ) ;
56 l i n k . c l o s e ( ) ; // Step 5 .
57 }
58 c a t c h ( IOException ioEx )
59 {
60 System . out . p r i n t l n ( ” Unable t o d i s c o n n e c t ! ” ) ;
61 System . e x i t ( 1 ) ;
62 }
63 }
64 }
65 }
Listing 1.2: TCP Server with ServerSocket
Setting up the corresponding client involves four steps
1. Establish a connection to the server.
We create a Socket object, supplying its constructor with the following two arguments:
• the servers IP address (of type InetAddress );
• the appropriate port number for the service.(The port number for server and client programs must be
the same, of course!)

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 13


Advance Java Sumit A. Khatri

For simplicitys sake, we shall place client and server on the same host, which will allow us to retrieve the
IP address by calling static method getLocalHost of class InetAddress . For example:

Socket link = new Socket(InetAddress.getLocalHost(),1234);

2. Set up input and output streams.


These are set up in exactly the same way as the server streams were set up (by calling methods getInput-
Stream and getOutputStream of the Socket object that was created in step 2).
3. Send and receive data.
The Scanner object at the client end will receive messages sent by the PrintWriter object at the server end,
while the PrintWriter object at the client end will send messages that are received by the Scanner object
at the server end (using methods next- Line and println respectively).
4. Close the connection.
This is exactly the same as for the server process (using method close of class Socket ).

The code below shows the client program for our example. In addition to an input stream to accept messages
from the server, our client program will need to set up an input stream (as another Scanner object) to accept
user messages from the keyboard. As for the server, the lines of code corresponding to each of the above steps
have been clearly marked with comments.
1 im po rt j a v a . i o . ∗ ;
2 im po rt j a v a . n e t . ∗ ;
3 im po rt j a v a . u t i l . ∗ ;
4 p u b l i c c l a s s TCPEchoClient
5 {
6 private s t a t i c InetAddress host ;
7 p r i v a t e s t a t i c f i n a l i n t PORT = 1 2 3 4 ;
8 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
9 {
10 try
11 {
12 host = InetAddress . getLocalHost () ;
13 }
14 c a t c h ( UnknownHostException uhEx )
15 {
16 System . out . p r i n t l n ( ” Host ID not found ! ” ) ;
17 System . e x i t ( 1 ) ;
18 }
19 accessServer () ;
20 }
21 pri vate s t a t i c void a c c e s s S e r v e r ( )
22 {
23 S o c k e t l i n k = n u l l ; // Step 1 .
24 try
25 {
26 l i n k = new S o c k e t ( ho st ,PORT) ; // Step 1 .
27 S c a n n e r i n p u t = new S c a n n e r ( l i n k . g e t I n p u t S t r e a m ( ) ) ; // Step 2 .
28 P r i n t W r i t e r ou tp ut = new P r i n t W r i t e r ( l i n k . getOutputStream ( ) , t r u e ) ; // Step 2 .
29 // S e t up stream f o r keyboard e n t r y
30 S c a n n e r u s e r E n t r y = new S c a n n e r ( System . i n ) ;
31 S t r i n g message , r e s p o n s e ;
32 do
33 {
34 System . out . p r i n t ( ” Enter message : ” ) ;
35 message = u s e r E n t r y . n e x t L i n e ( ) ;
36 ou t put . p r i n t l n ( message ) ; // Step 3 .
37 r e s p o n s e = i n p u t . n e x t L i n e ( ) ; // Step 3 .
38 System . out . p r i n t l n ( ” \nSERVER> ”+r e s p o n s e ) ;
39 } w h i l e ( ! message . e q u a l s ( ” ∗∗∗CLOSE∗∗∗ ” ) ) ;
40 }
41 c a t c h ( IOException ioEx )
42 {
43 ioEx . p r i n t S t a c k T r a c e ( ) ;
44 }
45 finally
46 {
47 try
48 {
49 System . out . p r i n t l n ( ” \n∗ C l o s i n g c o n n e c t i o n ∗” ) ;

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 14


Advance Java Sumit A. Khatri

50 l i n k . c l o s e ( ) ; // Step 4 .
51 }
52 c a t c h ( IOException ioEx )
53 {
54 System . out . p r i n t l n ( ” Unable t o d i s c o n n e c t ! ” ) ;
55 System . e x i t ( 1 ) ;
56 }
57 }
58 }
59 }
Listing 1.3: TCP Client with Socket

For the preceding clientserver application to work, TCP/IP must be installed and working. How are you to know
whether this is the case for your machine? Well, if there is a working Internet connection on your machine, then
TCP/IP is running. In order to start the application, first open two command windows and then start the server
running in one window and the client in the other. (Make sure that the server is running first, in order to avoid
having the client program crash!).
The output of above code is left for you as an assignment.

1.5.4 DatagramSocket and DatagramPacket class


For many applications the convenience of the TCP sockets outweighs the overhead required. However, for certain
applications it is much more efficient to utilize connectionless communications via datagrams: small, fixed-length
messages sent between computers of a network.
A TCP connection carries a number of overhead. First, one needs to go through several steps to open a
connection. This takes certain time. Once a connection is open, sending and receiving data each involving several
steps. The final step is to tear down the connection after the communication. If one is to send large amount of
data that must be reliably delivered, then the TCP protocol is suitable. However, if one only needs to send a
short, simple message quickly, then all these steps may not be worthwhile.
The difference between datagram and TCP connections is like the difference between pagers and telephones.
With a telephone, you make a connection to a specific telephone number, if the person on the destination answers
the phone, you two are able to talk for certain period of time, exchanging arbitrary amount of information, and
then you close the connction. With a pager, you typically send a message via a radio tower one-way to a tiny
radio receiver. Because of broadcast difficulties and delays you cannot be certain if or when the paged party
receives the message. The only way to tell is if you request and receive some kind of acknowledgement. You may
retry several times if you get no response, then give up.
On an IP network such as the Internet, the UDP (Unreliable Datagram Protocol) is used to transmit fixed-
length datagrams. This is the protocol that Java taps with the DatagramSocket class. Protocols that use UDP
include NFS, FSP, and TFTP.
Datagrams have the following advantages:
• Speed. UDP involves low overhead since there is no need to set up the connection, to maintain the order
and correctness of the message delivery, and to tear down the connection after the communication.
• Message-oriented instead of stream-oriented. If the message to be sent is small and simple, it may
be easier to simply send the chunk of bytes instead of going through the steps of converting it to and from
streams.
Two java.net classes define the heart of datagram-based messaging in Java, the DatagramSocket and the Data-
gramPacket.
The DatagramSocket is the interface through which DatagramPacket are transmitted. A DatagramPacket is
simply an IP-specific wrapper for a block of data.

1.5.4.1 The DatagramSocket Class


The DatagramSocket class provides a good interface to the UDP protocol. This class is responsible for sending
and receiving DatagramPacket via the UDP protocol. The most commonly used DatagramSocket methods and
constructors are listed below:
• DatagramSocket() Constructor constructs a datagram socket and binds it to any available port on the
local host machine.
• DatagramSocket(int port) Constructor constructs a datagram socket and binds it to the specified port on
the local host machine.

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 15


Advance Java Sumit A. Khatri

• DatagramSocket(int port, InetAddress addr) Constructor creates a datagram socket, bound to the specified
local address and port.
• DatagramSocket(SocketAddress addr) Constructor creates a datagram socket, bound to the specified local
socket address.
• void receive(DatagramPacket p) Receive a DatagramPacket from any remote server.
• void send(DatagramPacket p) Send a DatagramPacket to the remote server specified in the DatagramPacket.
• void close() Tear down local communication resources. After this method has been called, release this
object.
• int getLocalPort() Returns the local port this DatagramSocket is using.
Note that there are two flavors of DatagramSocket: those create to send DatagramPackets, and those created
to receive DatagramPackets. A send DatagramSocket uses an ephemeral local port assigned by the native UDP
implementation. A receive DatagramSockect requires a specific local port number.

1.5.4.2 The DatagramPacket Class


A DatagramPacket represents the datagram transmitted via a DatagramSocket. The most frequently used meth-
ods of DatagramPacket are:
• DatagramPacket(byte[] buf, int length) Constructor constructs a DatagramPacket for receiving packets of
length length.
• DatagramPacket(byte[] buf, int length, InetAddress address, int port) Constructor constructs a datagram
packet for sending packets of length length to the specified port number on the specified host.
• DatagramPacket(byte[] buf, int offset, int length) Constructor constructs a DatagramPacket for receiving
packets of length length, specifying an offset into the buffer.
• DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port) Constructor constructs a
datagram packet for sending packets of length length with offset ioffsetto the specified port number on the
specified host.
• InetAddress getAddress() This method allows one to either obtain the InetAddress of the host that sent the
DatagramPacket, or to obtain the InetAddress of the host to which this packet is addressed.
• byte[] getData() This method allows one to access the raw binary data wrapped in the DatagramPacket.
• int getLength() This method allows one to determine the length of data wrapped in the DatagramPacket
without getting a reference to the data block itself.
• int getPort() This method returns either the port of the server to which this packet will be sent, else it
returns the port of the server that sent this packet, depending on whether the packet was built to be sent
or built to receive data.

1.5.4.3 Datagram (UDP/IP) Client-Server


Following the style of coverage for TCP client/server applications, the detailed steps required for client and server
will be described separately, with the server process being covered first. This process involves the following nine
steps, though only the first eight steps will be executed under normal circumstances
Setting up the Server Process:
1. Create a DatagramSocket object.
Just as for the creation of a ServerSocket object, this means supplying the objects constructor with the port
number. For example:

DatagramSocket datagramSocket = new DatagramSocket(1234);

2. Create a buffer for incoming datagrams.


This is achieved by creating an array of bytes. For example:

byte[] buffer = new byte[256];

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 16


Advance Java Sumit A. Khatri

3. Create a DatagramPacket object for the incoming datagrams.


The constructor for this object requires two arguments:
• the previously-created byte array;
• the size of this array.
For example:

DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);

4. Accept an incoming datagram.


This is effected via the receive method of our DatagramSocket object, using our DatagramPacket object as
the receptacle . For example:

datagramSocket.receive(inPacket);

5. Accept the senders address and port from the packet.


Methods getAddress and getPort of our DatagramPacket object are used for this. For example:

InetAddress clientAddress = inPacket.getAddress();


int clientPort = inPacket.getPort();

6. Retrieve the data from the buffer.


For convenience of handling, the data will be retrieved as a string, using an overloaded form of the String
constructor that takes three arguments:
• a byte array;
• the start position within the array (= 0 here);
• the number of bytes (= full size of buffer here).
For example:

String message = new String(inPacket.getData(),0,inPacket.getLength());

7. Create the response datagram.


Create a DatagramPacket object, using an overloaded form of the constructor that takes four arguments:
• the byte array containing the response message;
• the size of the response;
• the clients address;
• the clients port number.
The first of these arguments is returned by the getBytes method of the String class (acting on the desired
String response). For example:

DatagramPacket outPacket = new DatagramPacket(response.getBytes(),response.length(),clientAddress,


clientPort);
(Here, response is a String variable holding the return message.)

8. Send the response datagram.


This is achieved by calling method send of our DatagramSocket object, supplying our outgoing Datagram-
Packet object as an argument. For example:

datagramSocket.send(outPacket);

Steps 4 to 8 may be executed indefinitely (within a loop). Under normal circumstances, the
server would probably not be closed down at all. However, if an exception occurs, then the associated
DatagramSocket should be closed, as shown in step 9 below.
9. Close the DatagramSocket.
This is effected simply by calling method close of our DatagramSocket object. For example:

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 17


Advance Java Sumit A. Khatri

datagramSocket.close();

To illustrate the above procedure and to allow easy comparison with the equivalent TCP/IP code, the example
from Sect. 1.5.3.3 will be employed again. As before, the lines of code corresponding to each of the above steps
are indicated via emboldened comments. Note that the numMessages part of the message that is returned by the
server is somewhat artificial, since, in a real-world application, many clients could be making connection and the
overall message numbers would not mean a great deal to individual clients. However, the cumulative message-
numbering will serve to emphasise that there are no separate sockets for individual clients. There are two other
differences from the equivalent TCP/IP code that are worth noting, both concerning the possible exceptions that
may be generated:
• the IOException in main is replaced with a SocketException ;
• there is no checked exception generated by the close method in the finally clause, so there is no try block.
Now the code...
1 // S e r v e r t h a t e c h o e s back c l i e n t ’ s m e s s a g e s .
2 //At end o f d i a l o g u e , s e n d s message i n d i c a t i n g number o f
3 // m e s s a g e s r e c e i v e d . Uses datagrams .
4 im po rt j a v a . i o . ∗ ;
5 im po rt j a v a . n e t . ∗ ;
6 p u b l i c c l a s s UDPEchoServer
7 {
8 p r i v a t e s t a t i c f i n a l i n t PORT = 1 2 3 4 ;
9 p r i v a t e s t a t i c DatagramSocket datagramSocket ;
10 p r i v a t e s t a t i c DatagramPacket i n P a c k e t , o u t P a c k e t ;
11 p r i v a t e s t a t i c byte [ ] b u f f e r ;
12 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
13 {
14 System . out . p r i n t l n ( ” Opening p o r t \n” ) ;
15 try
16 {
17 datagramSocket = new DatagramSocket (PORT) ; // Step 1 .
18 }
19 c a t c h ( S o c k e t E x c e p t i o n sockEx )
20 {
21 System . out . p r i n t l n ( ” Unable t o open p o r t ! ” ) ;
22 System . e x i t ( 1 ) ;
23 }
24 handleClient () ;
25 }
26 pri vate s t a t i c void handleClient ( )
27 {
28 try
29 {
30 S t r i n g messageIn , messageOut ;
31 i n t numMessages = 0 ;
32 InetAddress clientAddress = null ;
33 int clientPort ;
34 do
35 {
36 b u f f e r = new b y t e [ 2 5 6 ] ; // Step 2 .
37 i n P a c k e t = new DatagramPacket ( b u f f e r , b u f f e r . l e n g t h ) ; // Step 3 .
38 datagramSocket . r e c e i v e ( i n P a c k e t ) ; // Step 4 .
39 c l i e n t A d d r e s s = i n P a c k e t . g e t A d d r e s s ( ) ; // Step 5 .
40 c l i e n t P o r t = i n P a c k e t . g e t P o r t ( ) ; // Step 5 .
41 m e s s a g e I n = new S t r i n g ( i n P a c k e t . getData ( ) , 0 , i n P a c k e t . g e t L e n g t h ( ) ) ; // Step 6 .
42 System . out . p r i n t l n ( ” Message r e c e i v e d . ” ) ;
43 numMessages++;
44 messageOut = ” Message ” + numMessages+ ” : ” + m e s s a g e I n ;
45 o u t P a c k e t = new DatagramPacket ( messageOut . g e t B y t e s ( ) , messageOut . l e n g t h ( ) , c l i e n t A d d r e s s ,
46 c l i e n t P o r t ) ; // Step 7 .
47 datagramSocket . send ( o u t P a c k e t ) ; // Step 8 .
48 } while ( true ) ;
49 }
50 c a t c h ( IOException ioEx )
51 {
52 ioEx . p r i n t S t a c k T r a c e ( ) ;
53 }
54 f i n a l l y // I f e x c e p t i o n thrown , c l o s e c o n n e c t i o n .
55 {
56 System . out . p r i n t l n ( ” \n∗ C l o s i n g c o n n e c t i o n ∗” ) ;
57 datagramSocket . c l o s e ( ) ; // Step 9 .

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 18


Advance Java Sumit A. Khatri

58 }
59 }
60 }
Listing 1.4: Server with DatagramSocket

Setting up the corresponding client requires the eight steps listed below.

1. Create a DatagramSocket object.


This is similar to the creation of a DatagramSocket object in the server program, but with the important
difference that the constructor here requires no argument, since a default port (at the client end) will be
used. For example:

DatagramSocket datagramSocket = new DatagramSocket();

2. Create the outgoing datagram.


This step is exactly as for step 7 of the server program. For example:

DatagramPacket outPacket = new DatagramPacket(message.getBytes(),message.length(), host, PORT);

3. Send the datagram message.


Just as for the server, this is achieved by calling method send of the DatagramSocket object, supplying our
outgoing DatagramPacket object as an argument. For example:

datagramSocket.send(outPacket);

Steps 4 to 6 below are exactly the same as steps 24 of the server procedure.
4. Create a buffer for incoming datagrams.
For example:

byte[] buffer = new byte[256];

5. Create a DatagramPacket object for the incoming datagrams.


For example:

DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);

6. Accept an incoming datagram.


For example:

datagramSocket.receive(inPacket);

7. Retrieve the data from the buffer.


This is the same as step 6 in the server program. For example:

String response = new String(inPacket.getData(),0,inPacket.getLength());

Steps 27 may then be repeated as many times as required.

8. Close the DatagramSocket.


This is the same as step 9 in the server program. For example:

datagramSocket.close();

As was the case in the server code, there is no checked exception generated by the above close method in the
fi nally clause of the client program, so there will be no try block. In addition, since there is no inter-message
connection maintained between client and server, there is no protocol required for closing down the dialogue. This
means that we do not wish to send the fi nal ***CLOSE*** string (though we shall continue to accept this from
the user, since we need to know when to stop sending messages at the client end). The line of code (singular, this
time) corresponding to each of the above steps will be indicated via an emboldened comment.
Now the code...

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 19


Advance Java Sumit A. Khatri

1 im po rt j a v a . i o . ∗ ;
2 im po rt j a v a . n e t . ∗ ;
3 im po rt j a v a . u t i l . ∗ ;
4 p u b l i c c l a s s UDPEchoClient
5 {
6 private s t a t i c InetAddress host ;
7 p r i v a t e s t a t i c f i n a l i n t PORT = 1 2 3 4 ;
8 p r i v a t e s t a t i c DatagramSocket datagramSocket ;
9 p r i v a t e s t a t i c DatagramPacket i n P a c k e t , o u t P a c k e t ;
10 p r i v a t e s t a t i c byte [ ] b u f f e r ;
11 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
12 {
13 try
14 {
15 host = InetAddress . getLocalHost () ;
16 }
17 c a t c h ( UnknownHostException uhEx )
18 {
19 System . out . p r i n t l n ( ” Host ID not found ! ” ) ;
20 System . e x i t ( 1 ) ;
21 }
22 accessServer () ;
23 }
24 pri vate s t a t i c void a c c e s s S e r v e r ( )
25 {
26 try
27 {
28 // Step 1
29 datagramSocket = new DatagramSocket ( ) ;
30 // S e t up stream f o r keyboard e n t r y
31 S c a n n e r u s e r E n t r y = new S c a n n e r ( System . i n ) ;
32 S t r i n g message=” ” , r e s p o n s e=” ” ;
33 do
34 {
35 System . out . p r i n t ( ” Enter message : ” ) ;
36 message = u s e r E n t r y . n e x t L i n e ( ) ;
37 i f ( ! message . e q u a l s ( ” ∗∗∗CLOSE∗∗∗ ” ) )
38 {
39 o u t P a c k e t = new DatagramPacket ( message . g e t B y t e s ( ) , message . l e n g t h ( ) , ho st ,PORT) ; // Step2 .
40 // Step 3
41 datagramSocket . send ( o u t P a c k e t ) ;
42 b u f f e r = new b y t e [ 2 5 6 ] ; // Step 4 .
43 i n P a c k e t = new DatagramPacket ( b u f f e r , b u f f e r . l e n g t h ) ; // Step 5 .
44 // Step 6
45 datagramSocket . r e c e i v e ( i n P a c k e t ) ;
46 r e s p o n s e = new S t r i n g ( i n P a c k e t . getData ( ) , 0 , i n P a c k e t . g e t L e n g t h ( ) ) ; // Step 7 .
47 System . out . p r i n t l n ( ” \nSERVER> ”+r e s p o n s e ) ;
48 }
49 } w h i l e ( ! message . e q u a l s ( ” ∗∗∗CLOSE∗∗∗ ” ) ) ;
50 }
51 c a t c h ( IOException ioEx )
52 {
53 ioEx . p r i n t S t a c k T r a c e ( ) ;
54 }
55 finally
56 {
57 System . out . p r i n t l n ( ” \n∗ C l o s i n g c o n n e c t i o n ∗” ) ;
58 datagramSocket . c l o s e ( ) ; // Step 8 .
59 }
60 }
61 }
Listing 1.5: Client with DatagramSocket

For the preceding application to work, UDP must be installed and working on the host machine. As for TCP/IP,
if there is a working Internet connection on the machine, then UDP is running. Once again, in order to start the
application, first open two command windows and then start the server running in one window and the client in
the other. (Start the server before the client!)

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 20


Advance Java Sumit A. Khatri

1.5.5 The URL Class


1.5.5.1 Basics of URL Class
A URL, short for ”Uniform Resource Locator”, is a way to unambiguously identify the location of a resource on
the Internet. The simplest way for a Java program to locate and retrieve data from the network is to use the URL
class provided by Java in the java.net.URL. This class is an abstraction of a URL like http://www.gpnagpur.ac.in/.
The java.net.URL class represents a URL. There are constructors to create new URLs and methods to parse
the different parts of a URL. However the heart of the class are the methods that allow you to get an InputStream
from a URL so you can read data from a server.
The URL class is closely tied to protocol and content handlers. The objective is to separate the data being
downloaded from the the protocol used to download it. The protocol handler is responsible for communicating
with the server, that is moving bytes from the server to the client. It handles any necessary negotiation with the
server and any headers. Its job is to return only the actual bytes of the data or file requested. The content handler
takes those bytes and translates them into some kind of Java object such as an InputStream or ImageProducer.
When you construct a URL object, Java looks for a protocol handler that understands the protocol part of the
URL such as ”http” or ”mailto”. If no such handler is found, the constructor throws a MalformedURLException.
The protocols include ftp, http, file, gopher, mailto, etc.
You can create URL instances using its constructors. The simplest one is the constructor that takes an
absolute URL in string form as its single argument:
public URL(String url) throws MalformedURLException
Commonly used methods and constructors of Java URL class
• Constructors
– URL(String spec) Creates a URL object from the String representation.
– URL(String protocol, String host, int port, String file) Creates a URL object from the specified protocol,
host, port number, and file.
– URL(String protocol, String host, String file) Creates a URL from the specified protocol name, host
name, and file name.
– URL(URL context, String spec) Creates a URL by parsing the given spec within a specified context.
• Methods
– public String getProtocol() it returns the protocol of the URL.
– public String getHost() it returns the host name of the URL.
– public String getPort() it returns the Port Number of the URL.
– public String getFile() it returns the file name of the URL.
– public URLConnection openConnection() it returns the instance of URLConnection i.e. associated
with this URL.
In general, a URL can be broken into several parts. Consider the following example:
http://www.example.com/docs/resource1.html
A URL can optionally specify a ”port”, which is the port number to which the TCP connection is made on the
remote host machine. If the port is not specified, the default port for the protocol is used instead. For example,
the default port for http is 80. An alternative port could be specified as:
http://www.example.com:1080/docs/resource1.html
A URL may have appended to it a ”fragment”, also known as a ”ref” or a ”reference”. The fragment is indicated
by the sharp sign character ”# ” followed by more characters. For example,

http://java.sun.com/index.html# chapter1

This fragment is not technically part of the URL. Rather, it indicates that after the specified resource is
retrieved, the application is specifically interested in that part of the document that has the tag chapter1 attached
to it. The meaning of a tag is resource specific.
An application can also specify a ”relative URL”, which contains only enough information to reach the resource
relative to another URL. Relative URLs are frequently used within HTML pages. For example, if the contents of
the URL:

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 21


Advance Java Sumit A. Khatri

http://java.sun.com/index.html
contained within it the relative URL:
FAQ.html
it would be a shorthand for:
http://java.sun.com/FAQ.html
The relative URL need not specify all the components of a URL. If the protocol, host name, or port number is
missing, the value is inherited from the fully specified URL. The file component must be specified. The optional
fragment is not inherited.
Java program to show use of URL class:
1 // Java program t o d e m o n s t r a t e working o f URL
2 im po rt j a v a . n e t . MalformedURLException ;
3 im po rt j a v a . n e t .URL;
4
5 p u b l i c c l a s s URLclass1
6 {
7 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
8 throws MalformedURLException
9 {
10
11 // c r e a t e s a URL with s t r i n g r e p r e s e n t a t i o n .
12 URL u r l 1 = new URL( ” h t t p s : / /www. g o o g l e . co . i n /? g f e r d=c r&e i=ptYq” +
13 ”WK26I4fT8gfth6CACg#q=g e e k s+f o r+g e e k s+j a v a ” ) ;
14
15 // c r e a t e s a URL with a p r o t o c o l , hostname , and path
16 URL u r l 2 = new URL( ” h t t p ” , ”www. g e e k s f o r g e e k s . o r g ” ,
17 ” /jvm−works−jvm−a r c h i t e c t u r e / ” ) ;
18
19 URL u r l 3 = new URL( ” h t t p s : / /www. g o o g l e . co . i n / s e a r c h ? ”+
20 ”q=gnu&r l z =1C1CHZL enIN71” +
21 ” 4 IN715&oq=gnu&a q s=chrome . . 6 9 i 5 7 j 6 ” +
22 ” 9 i 6 0 l 5 . 6 5 3 j 0 j 7&s o u r c e i d=chrome&i e=UTF” +
23 ”−8#q=g e e k s+f o r+g e e k s+j a v a ” ) ;
24
25 // p r i n t t h e S t r i n g r e p r e s e n t a t i o n o f t h e URL.
26 System . out . p r i n t l n ( u r l 1 . t o S t r i n g ( ) ) ;
27 System . out . p r i n t l n ( u r l 2 . t o S t r i n g ( ) ) ;
28 System . out . p r i n t l n ( ) ;
29 System . out . p r i n t l n ( ” D i f f e r e n t components o f t h e URL3−” ) ;
30
31 // r e t r i e v e t h e p r o t o c o l f o r t h e URL
32 System . out . p r i n t l n ( ” P r o t o c o l :− ” + u r l 3 . g e t P r o t o c o l ( ) ) ;
33
34 // r e t r i e v e t h e hostname o f t h e u r l
35 System . out . p r i n t l n ( ” Hostname:− ” + u r l 3 . g e t H o s t ( ) ) ;
36
37 // r e t r i e v e t h e d e f a l u t p o r t
38 System . out . p r i n t l n ( ” D e f a u l t p o r t :− ” +
39 url3 . getDefaultPort () ) ;
40
41 // r e t r i e v e t h e query p a r t o f URL
42 System . out . p r i n t l n ( ” Query:− ” + u r l 3 . getQuery ( ) ) ;
43
44 // r e t r i v e t h e path o f URL
45 System . out . p r i n t l n ( ” Path:− ” + u r l 3 . getPath ( ) ) ;
46
47 // r e t r i v e t h e f i l e name
48 System . out . p r i n t l n ( ” F i l e :− ” + u r l 3 . g e t F i l e ( ) ) ;
49
50 // r e t r i e v e t h e r e f e r e n c e
51 System . out . p r i n t l n ( ” R e f e r e n c e :− ” + u r l 3 . g e t R e f ( ) ) ;
52 }
53 }
Listing 1.6: Example of Java URL class

1.5.6 The URLConnection and HttpURLConnection Class


In the section 1.5.5, we saw how we can create a URL object and get the information of any resource on the
internet. But barely getting the state-information is not the true motive of a real world application. To retrieve

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 22


Advance Java Sumit A. Khatri

the information, process it and sending the results back to the server, or just display the required information
retrieved from the server is what we are aiming at. Consider, for example a small application which asks for a
movie name from user and in turn returns the imdb rating of the movie or return all the links related to that
movie. All of this can be achieved using the URLConnection class. URLConnection is an abstract class whose
subclasses form the link between the user application and any resource on the web. We can use it to read/write
from/to any resource referenced by a URL object. URLConnection is an abstract class whose subclasses form the
link between the user application and any resource on the web. We can use it to read/write from/to any resource
referenced by a URL object. There are mainly two subclass that extends the URLConnection class-
• HttpURLConnection: If we are connecting to any url which uses http as its protocol, then HttpURL-
Connection class is used.
• JarURLConnection: If however, we are trying to establish a connection to a jar file on the web, then
JarURLConnection is used.
Once the connection is established and we have a URLConnection object, we can use it to read or write or get
further information about when was the page/file last modified, content length etc.
Displaying source code of a webpage by URLConnecton class: The URLConnection class provides many
methods, we can display all the data of a webpage by using the getInputStream() method. The getInputStream()
method returns all the data of the specified URL in the stream that can be read and displayed.
1 im po rt j a v a . i o . ∗ ;
2 im po rt j a v a . n e t . ∗ ;
3 p u b l i c c l a s s URLConnectionExample
4 {
5 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
6 {
7 try
8 {
9 URL u r l=new URL( ” h t t p s : / /www. c o u r s e r a . o r g / s p e c i a l i z a t i o n s /web−d e s i g n ” ) ;
10 URLConnection u r l c o n=u r l . o penConn ectio n ( ) ;
11 InputStream stream=u r l c o n . g e t I n p u t S t r e a m ( ) ;
12 int i ;
13 w h i l e ( ( i=stream . r e a d ( ) ) !=−1)
14 {
15 System . out . p r i n t ( ( c h a r ) i ) ;
16 }
17 }
18 c a t c h ( E x c e p t i o n e ) { System . out . p r i n t l n ( e ) ; }
19 }
20 }
Listing 1.7: Example of Java URLConnection class

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.
By the help of HttpURLConnection class, you can get information of any HTTP URL such as header infor-
mation, status code, response code etc. The java.net.HttpURLConnection is subclass of URLConnection class.
We know that the openConnection() method of URL class returns the object of URLConnection class.
We can typecast it to HttpURLConnection type as given below.
URL url=new URL(”http://www.coursera.org/specializations/web-design”);
HttpURLConnection huc=(HttpURLConnection)url.openConnection();

1 im po rt j a v a . i o . ∗ ;
2 im po rt j a v a . n e t . ∗ ;
3 p u b l i c c l a s s HttpURLConnectionDemo
4 {
5 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
6 {
7 try
8 {
9 URL u r l=new URL( ” h t t p : / /www. c o u r s e r a . o r g / s p e c i a l i z a t i o n s /web−d e s i g n ” ) ;
10 HttpURLConnection huc=(HttpURLConnection ) u r l . ope nConnec tion ( ) ;
11 f o r ( i n t i =1; i <=8; i ++)
12 {
13 System . out . p r i n t l n ( huc . g e t H e a d e r F i e l d K e y ( i )+” = ”+huc . g e t H e a d e r F i e l d ( i ) ) ;
14 }
15 huc . d i s c o n n e c t ( ) ;
16 }
17 c a t c h ( E x c e p t i o n e ) { System . out . p r i n t l n ( e ) ; }
18 }

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 23


Advance Java Sumit A. Khatri

19 }
Listing 1.8: Example of Java HttpURLConnection class

1.6 REFERENCES
1. Java Network Programming Study Guide by Professor Wanlei Zhou, School of Information Technology,
Deakin University
2. http://nptel.ac.in/courses/106105084/30

3. An Introduction to Network Programming with Java, Jan Graba, Springer Edition


4. TCP/IP Tutorial and Technical Overview, IBM RedBook
5. Sockets and Client/Server Communication, Jeff Chase, Duke University
6. https://docs.oracle.com/javase/tutorial/networking/overview/networking.html

7. https://www.tutorialspoint.com/java/
8. https://www.javatpoint.com/java-networking
9. https://www.geeksforgeeks.org/java/

CHAPTER 1. NETWORKING AND SOCKET PROGRAMMING 24


Chapter 2

Java Database Connectivity

2.1 JDBC Introduction


The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database. Java Database Connectivity (JDBC) is an implementation of the Java programming language that
dictates how databases communicate with each other. Through a standardized application programming in-
terface (API), connectivity from database management systems (DBMS) to a wide range of SQL databases is
accomplished. Some of the advantages of JDBC are listed below:
• It is a database independent technology.
• No need to depend on JNI (Java Native Interface) to communicate with database system.

• JDBC is implemented on java programming language so all the benefits of java are inherited to JDBC
technology.
• It is open-source technology.
Many vendors and customers are now looking for easy database access for Java applications. Since Java is robust,
secure, easy to use, easy to understand, and automatically downloadable on a network, it is an excellent language
basis for the development of database applications. It offers many advantages over C, C++, Smalltalk, BASIC,
COBOL, and 4GLs for a wide variety of uses.
JDBC is a call level interface for java by using which we can connect with any database management system
and can perform DBMS operations on it. This API (Application Programming Interface) defined in the java.sql
package. JDBC helps you to write Java applications that manage these three programming activities:

1. Connect to a data source, like a database


2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query
The following simple code fragment gives a simple example of these three steps:
1 p u b l i c v o i d connectToAndQueryDatabase ( S t r i n g username , S t r i n g password ) {
2
3 //STEP 1 :
4 C o n n e c t i o n con = DriverManager . g e t C o n n e c t i o n ( ” j d b c : myDriver : myDatabase ” , username , password ) ;
5
6 //STEP 2 :
7 Statement stmt = con . c r e a t e S t a t e m e n t ( ) ;
8 R e s u l t S e t r s = stmt . e x e c u t e Q u e r y ( ”SELECT a , b , c FROM Table1 ” ) ;
9
10 //STEP 3 :
11 while ( r s . next ( ) ) {
12 i n t x = r s . g e t I n t ( ”a” ) ;
13 S t r i n g s = r s . g e t S t r i n g ( ”b” ) ;
14 f l o a t f = rs . getFloat (”c”) ;
15 }
16 }
Listing 2.1: Steps of JDBC

25
Advance Java Sumit A. Khatri

This short code fragment instantiates a DriverManager object to connect to a database driver and log into
the database, instantiates a Statement object that carries your SQL language query to the database; instantiates
a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and
displays those results. It’s that simple.

2.2 JDBC Architecture


The JDBC API supports both two-tier and three-tier processing models for database access.

2.2.1 Two-tier and Three-tier Processing Models

Figure 2.1: Two-Tier Architecture for Data Access

Figure 2.2: Three-Tier Architecture for Data Access

In the two-tier model shown in Figure 2.1, a Java applet or application talks directly to the data source. This
requires a JDBC driver that can communicate with the particular data source being accessed. A user’s commands
are delivered to the database or other data source, and the results of those statements are sent back to the user.
The data source may be located on another machine to which the user is connected via a network. This is referred
to as a client/server configuration, with the user’s machine as the client, and the machine housing the data source
as the server. The network can be an intranet, which, for example, connects employees within a corporation, or
it can be the Internet.
In the three-tier model shown in Figure 2.2, commands are sent to a ”middle tier” of services, which then
sends the commands to the data source. The data source processes the commands and sends the results back
to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive
because the middle tier makes it possible to maintain control over access and the kinds of updates that can be
made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many
cases, the three-tier architecture can provide performance advantages.

2.3 JDBC Components


JDBC includes four components:

CHAPTER 2. JAVA DATABASE CONNECTIVITY 26


Advance Java Sumit A. Khatri

1. The JDBC API:


The JDBC API provides programmatic access to relational data from the Java programming language.
Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes
back to an underlying data source. The JDBC API can also interact with multiple data sources in a
distributed, heterogeneous environment. The JDBC API is part of the Java platform, which includes the
Java Standard Edition (Java SE ) and the Java Enterprise Edition(Java EE). The JDBC 4.0 API is divided
into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.
2. JDBC Driver Manager:
The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver.
DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.
The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered
with a Java Naming and Directory Interface (JNDI) naming service to establish a connection with a data
source. You can use either connecting mechanism, but using a DataSource object is recommended whenever
possible.

3. JDBC Test Suite:


The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests
are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC
API.
4. JDBC-ODBC Bridge:
The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC
binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate
on a corporate network where client installations are not a major problem, or for application server code
written in Java in a three-tier architecture

2.4 JDBC Drivers


JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert requests
from Java programs to a protocol that the DBMS can understand.
To connect with individual databases, JDBC requires drivers for each database. Those drivers come in four
varieties. Driver types 1 and 2 are typically intended for programmers that write applications. Driver types 3 and
4 are typically used by database and middleware vendors. The various driver types are described in the following
sub-sections:
• Type I: JDBC-ODBC Bridge
• Type II: Partial Java driver

• Type III: Pure Java driver for database middleware


• Type IV: Direct-to-database pure Java driver

2.4.1 Type I: JDBC-ODBC Bridge


Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. Type-1 driver is also called Universal
driver because it can be used to connect to any of the databases.
This combination provides JDBC access via ODBC drivers. ODBC binary code–and in many cases, database
client code–must be loaded on each client machine that uses a JDBC-ODBC Bridge. A product called SequeLink
from Data Direct Technologies provides a driver that supports some ODBC drivers (for example Microsoft Access).
Type one drivers provide JDBC access via one or more Open Database Connectivity (ODBC) drivers. ODBC,
which predates JDBC, is widely used by developers to connect to databases in a non-Java environment.
A JDBC/ODBC bridge provides JDBC API access through one or more ODBC drivers. Some ODBC native
code and in many cases native database client code must be loaded on each client machine that uses this type of
driver.

Advantages:

CHAPTER 2. JAVA DATABASE CONNECTIVITY 27


Advance Java Sumit A. Khatri

• The only way to gain access to some low-end desktop databases.


• A good approach for learning JDBC.
• Allows access to almost any database since the database ODBC drivers are readily available.
Disadvantages:
• Not for large-scale applications.
• Performance suffers because theres some overhead associated with the translation work to go from JDBC
to ODBC.
• Doesnt support all the features of Java. User is limited by the functionality of the underlying ODBC driver.

2.4.2 Type II: Partial Java driver


This driver is also known as Native-API driver. The Native API driver uses the client -side libraries of the
database. This driver converts JDBC method calls into native calls of the database API. In order to interact with
different database, this driver needs their local API, thats why data transfer is much more secure as compared to
type-1 driver.
This type of driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or
other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on
each client machine.
A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for
DBMSs. Like the bridge driver, this style of driver requires that some binary code be loaded on each client
machine. An example of this type of driver is the Oracle Thick Driver, which is also called OCI.
Advantages:
• Performance is better than that of Type 1, in part because the Type 2 driver contains compiled code thats
optimized for the back-end database servers operating system.
• Allows access to almost any database since the databases ODBC drivers are readily available
• Offers significantly better performance than the JDBC/ODBC Bridge
Disadvantage
• User needs to make sure the JDBC driver of the database vendor is loaded onto each client machine.
• Must have compiled code for every operating system that the application will run on.
• Type 2 driver shows lower performance than type 3 or 4

2.4.3 Type III: Pure Java driver for database middleware


This driver is also known as Type-3 driver or Network Protocol driver. This style of driver translates JDBC calls
into the middleware vendors protocol, which is then translated to a DBMS protocol by a middleware server. The
middleware provides connectivity to many different databases.
This driver translates JDBC calls into the middleware vendors protocol, which is then converted to a database-
specific protocol by the middleware server software.
Here all the database connectivity drivers are present in a single server, hence no need of individual client-side
installation.

Advantages:
• Better performance than Types 1 and 2.
• Can be used when a company has multiple databases and wants to use a single JDBC driver to connect to
all of them.
• Server-based, so no need for JDBC driver code on client machine.
• For performance reasons, the back-end server component is optimized for the operating system on which
the database is running. calable
• Caching

CHAPTER 2. JAVA DATABASE CONNECTIVITY 28


Advance Java Sumit A. Khatri

• Advanced system administration


• Does not require applicable database client libraries
Disadvantages:

• Needs some database-specific code on the middleware server.


• If the middleware must run on different platforms, a Type 4 driver might be more effective.
• Network support is required on client machine.
• Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier.

2.4.4 Type IV: Direct-to-database pure Java driver


This driver is also known as Thin driver.This is a native-protocol, fully Java technology-enabled driver which
converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from
the client machine to the DBMS server. This type of driver has become very popular recently and is supported
by most database software vendors. All JDBC drivers from Data Direct Technologies (driver vendor) are Type 4
drivers.
Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not
require any native database library, that is why it is also known as Thin Driver.

Advantages:
• Better performance than Types 1 and 2.
• No need to install special software on client or server.

• Scalable
• Caching
• Advanced system administration
• Superior performance

• Advance Java feature set


• Does not require applicable database client libraries
Disadvantages:

• Not optimized for server operating system, so the driver cant take advantage of operating system features.
(The driver is optimized for the database and can take advantage of the database vendors functionality.)
• User needs a different driver for each different database.

2.4.5 Which Driver to use When?


• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is
type-4.
• If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred
driver.

• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for your database.
• The type 1 driver is not considered a deployment-level driver, and is typically used for development and
testing purposes only.

CHAPTER 2. JAVA DATABASE CONNECTIVITY 29


Advance Java Sumit A. Khatri

2.5 Security Considerations


Tere are two main JDBC scenarios to consider for security purposes:
• In the case of Java applications, the Java code is ”trusted”. We also consider trusted applets in this category
for security purposes.
• In contrast, untrusted Java applets are not permitted access to local files and or network connections to
arbitrary hosts.

2.5.1 JDBC and untrusted applets


JDBC should follow the standard applet security model. Specifically:

• JDBC should assume that normal unsigned applets are untrustworthy


• JDBC should not allow untrusted applets access to local database data

• If a downloaded JDBC Driver registers itself with the JDBC DriverManager, then JDBC should only use
that driver to satisfy connection requests from code which has been loaded from the same source as the
driver.
• An untrusted applet will normally only be allowed to open a database connection back to the server from
which it was downloaded
• JDBC should avoid making any automatic or implicit use of local credentials when making connections to
remote database servers.

2.5.2 JDBC and Java applications


For a normal Java application (i.e. all Java code other than untrusted applets) JDBC should happily load drivers
from the local classpath and allow the application free access to files, remote servers, etc. However as with applets,
if for some reason an untrusted sun.sql.Driver class is loaded from a remote source, then that Driver should only
be used with code loaded from that same source.

2.5.3 Network security


The security of database requests and data transmission on the network, especially in the Internet case, is also
an important consideration for the JDBC user. The network protocols used for database access have generally
already been fixed by the DBMS vendor or connectivity vendor. JDBC users should verify that the network
protocol provides adequate security for their needs before using a JDBC driver and DBMS server.

2.5.4 Security Responsibilities of Drivers


Because JDBC drivers may be used in a variety of different situations, it is important that driver writers follow
certain simple security rules to prevent applets from making illegal database connections. These rules are un-
necessary if a driver is downloaded as an applet, because the standard security manager will prevent an applet
driver from making illegal connections. However JDBC driver writers should bear in mind that if their driver is
”successful” then users may start installing it on their local disks, in which case it becomes a trusted part of the
Java environment, and must make sure it is not abused by visiting applets. We therefore urge all JDB driver
writers to follow the basic security rules.

2.6 Database connectivity using JDBC API


A JDBC (Java Database Connectivity) program comprises the following steps:
1. Allocate a Connection object, for connecting to the database server.

2. Allocate a Statement object, under the Connection object created, for holding a SQL command.
3. Write a SQL query and execute the query, via the Statement and Connection created.
4. Process the query result.

CHAPTER 2. JAVA DATABASE CONNECTIVITY 30


Advance Java Sumit A. Khatri

5. Close the Statement and Connection object to free up the resources.


JDBC cycle illustrating the above steps is shown in the Figure 2.3 We shall illustrate Java Database program-
ming by the following examples.

2.6.1 Example 1: SQL SELECT


Try out the following JDBC program (requires JDK 1.7 and above), which issues an SQL SELECT. Take note
that the source filename must be the same as the classname, with extension of ”.java”.
1 im po rt j a v a . s q l . ∗ ; // Use ’ C o n n e c t i o n ’ , ’ Statement ’ and ’ R e s u l t S e t ’ c l a s s e s i n j a v a . s q l
package
2
3 // JDK 1 . 7 and above
4 public c l a s s JdbcSelectTest { // Save a s ” J d b c S e l e c t T e s t . j a v a ”
5 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
6 try (
7 // Step 1 : A l l o c a t e a d a t a b a s e ’ C o n n e c t i o n ’ o b j e c t
8 C o n n e c t i o n conn = DriverManager . g e t C o n n e c t i o n (
9 ” j d b c : mysql : / / l o c a l h o s t : 3 3 0 6 / ebookshop ” , ” myuser ” , ” xxxx ” ) ;
10 // MySQL : ” j d b c : mysql : / / hostname : p o r t / databaseName ” , ” username ” , ” password ”
11
12 // Step 2 : A l l o c a t e a ’ Statement ’ o b j e c t i n t h e C o n n e c t i o n
13 Statement stmt = conn . c r e a t e S t a t e m e n t ( ) ;
14 ){
15 // Step 3 : Execute a SQL SELECT query , t h e query r e s u l t
16 // i s returned in a ’ ResultSet ’ object .
17 S t r i n g s t r S e l e c t = ” s e l e c t t i t l e , p r i c e , qty from books ” ;
18 System . out . p r i n t l n ( ”The SQL query i s : ” + s t r S e l e c t ) ; // Echo For d e b u g g i n g
19 System . out . p r i n t l n ( ) ;
20
21 R e s u l t S e t r s e t = stmt . e x e c u t e Q u e r y ( s t r S e l e c t ) ;
22
23 // Step 4 : P r o c e s s t h e R e s u l t S e t by s c r o l l i n g t h e c u r s o r f o r w a r d v i a n e x t ( ) .
24 // For each row , r e t r i e v e t h e c o n t e n t s o f t h e c e l l s with getXxx ( columnName ) .
25 System . out . p r i n t l n ( ”The r e c o r d s s e l e c t e d a r e : ” ) ;
26 i n t rowCount = 0 ;
27 while ( r s e t . next ( ) ) { // Move t h e c u r s o r t o t h e n e x t row , r e t u r n f a l s e i f no more row
28 String t i t l e = rset . getString (” t i t l e ”) ;
29 double p r i c e = r s e t . getDouble ( ” p r i c e ” ) ;
30 int qty = r s e t . g e t I n t ( ” qty ” ) ;
31 System . out . p r i n t l n ( t i t l e + ” , ” + p r i c e + ” , ” + qty ) ;
32 ++rowCount ;
33 }
34 System . out . p r i n t l n ( ” T o t a l number o f r e c o r d s = ” + rowCount ) ;
35
36 } c a t c h ( SQLException ex ) {
37 ex . p r i n t S t a c k T r a c e ( ) ;
38 }
39 // Step 5 : C l o s e t h e r e s o u r c e s − Done a u t o m a t i c a l l y by t r y −with−r e s o u r c e s
40 }
41 }
Listing 2.2: SQL select with JDBC on MYSQL

1. The JDBC operations are carried out through the ”Connection”, ”Statement” and ”ResultSet” objects
(defined in package java.sql). However, you need not know the details, but merely the public methods
defined in the API (Application Program Interface). You also need not re-invent the wheels by creating
these classes yourself (which will take you many years?!). ”Re-using” software component is a main strength
of OOP.
2. Notice that there is little programming involved in using JDBC programming. You only have to specify
the database-URL, write the SQL query, and process the query result. The rest of the codes are kind of
”standard JDBC program template”. Again, this is because the wheels have been invented.
3. In Line 8, we allocate a Connection object (called conn) via static method DriverManager.getConnection(database-
url, db-user, password). The Java program uses a so-called database-URL to connect to the server:
For MySQL:
1 // Syntax
2 C o n n e c t i o n conn = DriverManager . g e t C o n n e c t i o n ( ” j d b c : mysql : / / l o c a l h o s t : { p o r t }/{ db−name} ” , ” {
db−u s e r } ” , ” { password } ” ) ;

CHAPTER 2. JAVA DATABASE CONNECTIVITY 31


Advance Java Sumit A. Khatri

3 // Example
4 C o n n e c t i o n conn = DriverManager . g e t C o n n e c t i o n ( ” j d b c : mysql : / / l o c a l h o s t : 3 3 0 6 / ebookshop ” , ”
myuser ” , ” xxxx ” ) ;
Listing 2.3: URL for MYSQL

The database-url is in the form of ”jdbc:mysql://host:port/database-name”, with protocol jdbc and sub-
protocol mysql. The port specifies the MySQL server’s TCP port number; db-user/password is an authorized
MySQL user. In our example, ”localhost” (with special IP address of 127.0.0.1) is the hostname for local
loop-back; ”3306” is the server’s TCP port number, and ebookshop is the database name.
ASSIGNMENT: Investigate the connection URL for other databases.
4. In Line 13, we allocate a Statement object (called stmt) within the Connection via conn.createStatement().
5. To execute a SQL SELECT command, we invoke method stmt.executeQuery(”SELECT ...”). It returns the
query result in a ResultSet object (called rset). ResultSet models the returned table, which can be access
via a row cursor. The cursor initially positions before the first row in the ResultSet. rset.next() moves the
cursor to the first row. You can then use rset.getXxx(columnName) to retrieve the value of the column
for that row, where Xxx corresponds to the type of the column, such as int, float, double and String. The
rset.next() returns false at the last row, which terminates the while-loop.
6. You may use rset.getString(columnName) to retrieve all types (int, double, etc).
7. For maximum portability, ResultSet columns within each row should be read in left-to-right order, and each
column should be read only once via the getXxx() methods. Issue getXxx() to a cell more than once may
trigger a strange error.
8. In this example, we use JDK 1.7’s new feature called try-with-resources, which automatically closes all the
opened resources in the try-clause, in our case, the Connection and Statement objects.

Exercises: Modify your Java program to issue the following SELECT statements and display all the columns
retrieved. Make sure you modify the ResultSet processing to process only the columns retrieved (otherwise, you
will get a ”Column not found” error).
1. SELECT * FROM books
2. SELECT title, author, price, qty FROM books WHERE author = ’Tan Ah Teck’ OR price ¿= 30 ORDER
BY price DESC, id ASC

2.6.2 Example 2: SQL UPDATE


To execute a SQL UPDATE, you have to invoke the method executeUpdate() of the Statement object, which
returns an int indicating the number of records affected. Recall that for SELECT, we use executeQuery(), which
returns a ResultSet object modeling the returned table. SQL UPDATE—INSERT—DELETE does not return a
table, but an int indicating the number of records affected.
1 im po rt j a v a . s q l . ∗ ; // Use c l a s s e s i n j a v a . s q l package
2
3 // JDK 1 . 7 and above
4 p u b l i c c l a s s JdbcUpdateTest { // Save a s ” JdbcUpdateTest . j a v a ”
5 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
6 try (
7 // Step 1 : A l l o c a t e a d a t a b a s e ’ C o n n e c t i o n ’ o b j e c t
8 C o n n e c t i o n conn = DriverManager . g e t C o n n e c t i o n (
9 ” j d b c : mysql : / / l o c a l h o s t : 3 3 0 6 / ebookshop ” , ” myuser ” , ” xxxx ” ) ; // MySQL
10
11 // Step 2 : A l l o c a t e a ’ Statement ’ o b j e c t i n t h e C o n n e c t i o n
12 Statement stmt = conn . c r e a t e S t a t e m e n t ( ) ;
13 ) {
14 // Step 3 & 4 : Execute a SQL UPDATE v i a e x e c u t e U p d a t e ( )
15 // which r e t u r n s an i n t i n d i c a t i n g t h e number o f rows a f f e c t e d .
16 // I n c r e a s e t h e p r i c e by 7% and qty by 1 f o r i d =1001
17 S t r i n g s t r U p d a t e = ” update books s e t p r i c e = p r i c e ∗ 0 . 7 , qty = qty+1 where i d = 1001 ” ;
18 System . out . p r i n t l n ( ”The SQL query i s : ” + s t r U p d a t e ) ; // Echo f o r d e b u g g i n g
19 i n t countUpdated = stmt . e x e c u t e U p d a t e ( s t r U p d a t e ) ;
20 System . out . p r i n t l n ( countUpdated + ” r e c o r d s a f f e c t e d . ” ) ;
21
22 // Step 3 & 4 : I s s u e a SELECT t o c h e c k t h e UPDATE.
23 S t r i n g s t r S e l e c t = ” s e l e c t ∗ from books where i d = 1001 ” ;
24 System . out . p r i n t l n ( ”The SQL query i s : ” + s t r S e l e c t ) ; // Echo f o r d e b u g g i n g

CHAPTER 2. JAVA DATABASE CONNECTIVITY 32


Advance Java Sumit A. Khatri

25 R e s u l t S e t r s e t = stmt . e x e c u t e Q u e r y ( s t r S e l e c t ) ;
26 while ( r s e t . next ( ) ) { // Move t h e c u r s o r t o t h e n e x t row
27 System . out . p r i n t l n ( r s e t . g e t I n t ( ” i d ” ) + ” , ”
28 + r s e t . g e t S t r i n g ( ” author ” ) + ” , ”
29 + rset . getString (” t i t l e ”) + ” , ”
30 + r s e t . getDouble ( ” p r i c e ” ) + ” , ”
31 + r s e t . g e t I n t ( ” qty ” ) ) ;
32 }
33 } c a t c h ( SQLException ex ) {
34 ex . p r i n t S t a c k T r a c e ( ) ;
35 }
36 // Step 5 : C l o s e t h e r e s o u r c e s − Done a u t o m a t i c a l l y by t r y −with−r e s o u r c e s
37 }
38 }
Listing 2.4: SQL Update with JDBC on MYSQL

Exercises: Modify your Java program to issue the following SQL statements:
1. Increase the price by 50% for ”A Cup of Java”.
2. Set the qty to 0 for ”A Teaspoon of Java”.

Figure 2.3: JDBC Cycle

2.7 References
1. https://docs.oracle.com/cd/E19509-01/820-5069/6ngg83nai/index.html

2. https://web.mit.edu/java_v1.5.0_22/distrib/share/docs/guide/jdbc/getstart/GettingStartedTOC.
fm.html
3. http://www.ntu.edu.sg/home/ehchua/programming/java/jdbc_basic.html
4. http://www.cs.yorku.ca/tech/other/jdk1.2.1/docs/guide/jdbc/spec/jdbc-spec.frame5.html

5. https://www.geeksforgeeks.org/jdbc-drivers/

CHAPTER 2. JAVA DATABASE CONNECTIVITY 33


Chapter 3

REMOTE METHOD INVOCATION

3.1 Introduction
Distributed systems require that computations running in different address spaces, potentially on different hosts,
be able to communicate. For a basic communication mechanism, the Java language supports sockets, which
are flexible and sufficient for general communication. However, sockets require the client and server to engage
in applications-level protocols to encode and decode messages for exchange, and the design of such protocols is
cumbersome and can be error-prone.
An alternative to sockets is Remote Procedure Call (RPC), which abstracts the communication interface to
the level of a procedure call. Instead of working directly with sockets, the programmer has the illusion of calling
a local procedure, when in fact the arguments of the call are packaged up and shipped off to the remote target of
the call. RPC systems encode arguments and return values using an external data representation.
RPC, however, does not translate well into distributed object systems, where communication between program-
level objects residing in different address spaces is needed. In order to match the semantics of object invocation,
distributed object systems require remote method invocation or RMI. In such systems, a local surrogate
(stub) object manages the invocation on a remote object.
The Java language has extensive data communications facilities built right into the language. You don’t just
call function libraries provided by your operating system. Instead there is extensive language support for reading
and writing to sockets, for calling member functions of Java object instances running in Java virtual machine
processes on other machines, and for downloading code from other machines. This downloading is not just of
applets (though that is what Javas distributed computing features are perhaps most well know for).
The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual
machine to invoke methods on an object running in another Java virtual machine. RMI provides
for remote communication between programs written in the Java programming language.

3.2 Serialization, Deserialization and Object Persistence in Java


Java serialization enables developers to save a Java object to a binary format so that it can be persisted to a file
or transmitted over a network. Remote Method Invocation (RMI) uses serialization as a communication medium
between a client and a server.
Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or
database or can be sent through streams. The reverse process of creating object from sequence of bytes is called
deserialization.
A class must implement Serializable interface present in java.io package in order to serialize its object success-
fully. Serializable is a marker interface that adds serializable behaviour to the class implementing it.
Java provides Serializable API encapsulated under java.io package for serializing and deserializing objects
which include:
• java.io.serializable
• java.io.Externalizable
• ObjectInputStream
• ObjectOutputStream
Figure 3.1 shows Serialization and Deserialization in java.
writeObject() method of ObjectOutputStream class serializes an object and send it to the output stream.

34
Advance Java Sumit A. Khatri

Figure 3.1: Serialization and Deserialization

public final void writeObject(object x) throws IOException


readObject() method of ObjectInputStream class references object out of stream and deserialize it.
public final Object readObject() throws IOException,ClassNotFoundException
While serializing if you do not want any field to be part of object state then declare it either static or transient
based on your need and it will not be included during java serialization process.
Following is the code for Serializing an Object. Here, object of Studentinfo class is serialized using writeOb-
ject() method and written to student.ser file.
1 im po rt j a v a . i o . ∗ ;
2 c l a s s s t u d e n t i n f o implements S e r i a l i z a b l e
3 {
4 S t r i n g name ;
5 int rid ;
6 s t a t i c String contact ;
7 studentinfo ( string n , int r , string c )
8 {
9 t h i s . name = n ;
10 this . rid = r ;
11 this . contact = c ;
12 }
13 }
14
15 c l a s s Test
16 {
17 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
18 {
19 try
20 {
21 S t u d e n t i n f o s i = new s t u d e n t i n f o ( ”ABCD” , 1 0 4 , ” 110044 ” ) ;
22 F i l e O u t p u t S t r e a m f o s = new F i l e O u t p u t S t r e a m ( ” s t u d e n t . s e r ” ) ;
23 O b j e c t o u t p u t s t r e a m o o s = new ObjectOutputStream ( f o s ) ;
24 oos . writeObject ( s i ) ;
25 oos . c l o s e ( ) ;
26 fos . close () ;
27 }
28 catch ( Exception e )
29 {
30 e . printStackTrace () ;
31 }
32 }
33 }
Listing 3.1: Serializing an Object

CHAPTER 3. REMOTE METHOD INVOCATION 35


Advance Java Sumit A. Khatri

1 im po rt j a v a . i o ∗ ;
2 class DeserializationTest
3 {
4 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s )
5 {
6 s t u d e n t i n f o s i=n u l l ;
7 try
8 {
9 F i l e I n p u t S t r e a m f i s = new F i l e I n p u t S t r e a m ( ” s t u d e n t . s e r ” ) ;
10 ObjectOutputStream o i s = new ObjectOutputStream ( f i s ) ;
11 s i = ( studentinfo ) o i s . readObject () ;
12 }
13 catch ( Exception e )
14 {
15 e . printStackTrace () ; }
16 System . out . p r i n t l n ( s i . name ) ;
17 System . out . p r i n t l n ( s i . r i d ) ;
18 System . out . p r i n t l n ( s i . c o n t a c t ) ;
19 }
20 }
Listing 3.2: Deserialization of Object

When you compile and run above programs, you would notice in the output that Contact field is null because,it
was marked as static and as we have discussed earlier static fields does not get serialized. Static members are
never serialized because they are connected to class not object of class.
We can also say, Serialization is used for:

1. To save/persist state of an object.


2. To travel an object across a network.

Figure 3.2: Serialization and Deserialization in Network

Only those Objects can be serialized which implement java.io.Serializable interface. If a nonserializable object
is tried to be serialized, it will throw java.io.NotSerializableException. To make use of serialization we need to
implement the java.io.Serializable interface in any class we want serialized. There are no methods to implement
within the java.io.Serializable interface as it is a marker interface, which is an interface that identifies classes that
use it as being of a certain type, in this case serializable.
Now the most important question is where we can apply this concept of serialization. Because if we cannot
apply this, reading this core concept is worthless. As I have already explained that this process ensures persistence.
To ensure that Object get created with same information and state.

3.3 Java Distributed Object Model


3.3.1 Definition of Terms
In the Java distributed object model, a remote object is one whose methods can be invoked from another Java
Virtual Machine, potentially on a different host. An object of this type is described by one or more remote
interfaces, which are Java interfaces that declare the methods of the remote object.

CHAPTER 3. REMOTE METHOD INVOCATION 36


Advance Java Sumit A. Khatri

Remote method invocation (RMI) is the action of invoking a method of a remote interface on a remote object.
Most importantly, a method invocation on a remote object has the same syntax as a method invocation on a
local object.

3.3.2 The Distributed and Nondistributed Models Contrasted


The Java distributed object model is similar to the Java object model in the following ways:
• A reference to a remote object can be passed as an argument or returned as a result in any method invocation
(local or remote).

• A remote object can be cast to any of the set of remote interfaces supported by the implementation using
the built-in Java syntax for casting.
• The built-in Java instanceof operator can be used to test the remote interfaces supported by a remote
object.

The Java distributed object model differs from the Java object model in these ways:
• Clients of remote objects interact with remote interfaces, never with the implementation classes of those
interfaces.
• Nonremote arguments to, and results from, a remote method invocation are passed by copy rather than
by reference. This is because references to objects are only useful within a single virtual machine.

• A remote object is passed by reference, not by copying the actual remote implementation.
• The semantics of some of the methods defined by class Object are specialized for remote objects.
• Since the failure modes of invoking remote objects are inherently more complicated than the failure modes of
invoking local objects, clients must deal with additional exceptions that can occur during a remote method
invocation.

3.3.3 RMI Interfaces and Classes


The interfaces and classes that are responsible for specifying the remote behavior of the RMI system are defined
in the java.rmi and the java.rmi.server packages. Figure 3.3 shows the relationship between these interfaces and
classes:

Figure 3.3: RMI Interfaces and Classes

CHAPTER 3. REMOTE METHOD INVOCATION 37


Advance Java Sumit A. Khatri

3.3.3.1 The Remote Interface


In RMI, a remote interface is an interface that declares a set of methods that may be invoked from a remote Java
virtual machine. A remote interface must satisfy the following requirements:

• A remote interface must at least extend, either directly or indirectly, the interface java.rmi.Remote.
• Each method declaration in a remote interface or its super-interfaces must satisfy the requirements of a
remote method declaration as follows:
– A remote method declaration must include the exception java.rmi.RemoteException (or one of its
superclasses such as java.io.IOException or java.lang.Exception) in its throws clause, in addition to
any application-specific exceptions (note that application specific exceptions do not have to extend
java.rmi.RemoteException).
– In a remote method declaration, a remote object declared as a parameter or return value (either
declared directly in the parameter list or embedded within a non-remote object in a parameter) must
be declared as the remote interface, not the implementation class of that interface.

All remote interfaces extend, either directly or indirectly, the interface java.rmi.Remote. The interface java.rmi.Remote
is a marker interface that defines no methods as shown here:

public interface Remote {}

For example, the following code fragment defines a remote interface for a bank account that contains methods
that deposit to the account, get the account balance, and withdraw from the account:
1 im po rt j a v a . rmi . ∗ ;
2 public i n t e r f a c e BankAccount e x t e n d s Remote
3 {
4 public v o i d d e p o s i t ( f l o a t amount ) throws j a v a . rmi . RemoteException ;
5 public v o i d withdraw ( f l o a t amount ) throws OverdrawnException , j a v a . rmi . RemoteException ;
6 public f l o a t b a l a n c e ( ) throws j a v a . rmi . RemoteException ;
7 }
Listing 3.3: Interface for Bank Account

3.3.3.2 The RemoteException Class


The java.rmi.RemoteException class is the superclass of all exceptions that can be thrown by the RMI runtime.
To ensure the robustness of applications using the RMI system, each method declared in a remote interface
must specify java.rmi.RemoteException in its throws clause. java.rmi.RemoteException is thrown when a remote
method invocation fails (for example when the network fails or the server for the call cannot be reached). This
allows the application making the remote invocation to determine how best to deal with the remote exception.

3.3.3.3 The RemoteObject Class and its Subclasses


RMI server functions are provided by java.rmi.server.RemoteObject and its subclasses, java.rmi.server.RemoteServer
and java.rmi.server.UnicastRemoteObject:
• The java.rmi.server.RemoteObject class provides the remote semantics of Object by implementing methods
for hashCode, equals, and toString.
• The functions needed to create objects and export them (make them available remotely) are provided
abstractly by java.rmi.server.RemoteServer and concretely by its subclass(es). The subclass identifies the
semantics of the remote reference, for example whether the server is a single object or is a replicated object
requiring communications with multiple locations.
• The java.rmi.server.UnicastRemoteObject class defines a singleton (unicast) remote object whose references
are valid only while the server process is alive.

CHAPTER 3. REMOTE METHOD INVOCATION 38


Advance Java Sumit A. Khatri

3.3.3.4 Implementing a Remote Interface


The general rules for a class that implements a remote interface are as follows:
• The class usually extends java.rmi.server.UnicastRemoteObject, thereby inheriting the remote behavior
provided by the classes

java.rmi.server.RemoteObject and
java.rmi.server.RemoteServer.

• The class can implement any number of remote interfaces.

• The class can extend another remote implementation class.


• The class can define methods that do not appear in the remote interface, but those methods can only be
used locally and are not available remotely.
For example, the following code fragment defines the BankAcctImpl class, which implements the BankAccount
remote interface and which extends the java.rmi.server.UnicastRemoteObject class:
1 im po rt j a v a . rmi . RemoteException ;
2 im po rt j a v a . rmi . s e r v e r . UnicastRemoteObject ;
3 p u b l i c c l a s s BankAccountImpl e x t e n d s UnicastRemoteObject implements BankAccount
4 {
5 p u b l i c v o i d d e p o s i t ( f l o a t amount ) throws RemoteException
6 {
7 ...
8
9 // i m p l e m e n t a t i o n code f o r d e p o s i t method
10
11 ...
12 }
13 p u b l i c v o i d withdraw ( f l o a t amount ) throws OverdrawnException , RemoteException
14 {
15 ...
16
17 // i m p l e m e n t a t i o n code f o r withdraw method
18
19 ...
20 }
21 p u b l i c f l o a t b a l a n c e ( ) throws RemoteException
22 {
23 ...
24
25 // i m p l e m e n t a t i o n code f o r b a l a n c e method
26
27 ...
28 }
29 }
Listing 3.4: Implementing Bank Account Interface

Note that, a class that implements a remote interface can extend some other class besides java.rmi.server.UnicastRemoteObject.
However, the implementation class must then assume the responsibility for the correct remote semantics of the
hashCode, equals, and toString methods inherited from the Object class.

3.3.3.5 Locating Remote Objects


A simple bootstrap name server is provided for storing named references to remote objects. A remote object
reference can be stored using the URL-based methods of the class java.rmi.Naming. For a client to invoke a
method on a remote object, that client must first obtain a reference to the object. A reference to a remote
object is usually obtained as a return value in a method call. The RMI system provides a simple bootstrap name
server from which to obtain remote objects on given hosts. Thejava.rmi.Naming class provides Uniform Resource
Locator (URL) based methods to look up, bind, rebind, unbind, and list the name-object pairings maintained on
a particular host and port. Here’s an example, (without exception handling) of how to bind and look up remote
objects:

BankAccount acct = new BankAcctImpl();


String url = ”rmi://java.Sun.COM/account”;
// bind url to remote object

CHAPTER 3. REMOTE METHOD INVOCATION 39


Advance Java Sumit A. Khatri

java.rmi.Naming.bind(url, acct);
...
// lookup account
acct = (BankAccount)java.rmi.Naming.lookup(url);

When a server process wants to export some RMI-based service to clients, it does so by registering one or more
RMI-enabled objects with its local RMI registry (represented by the Registry interface). Each object is registered
with a name clients can use to reference it. A client can obtain a stub reference to the remote object by asking
for the object by name through the Naming interface. The Naming.lookup() method takes the fully qualified
name of a remote object and locates the object on the network. The object’s fully qualified name is in a URL-like
syntax that includes the name of the object’s host and the object’s registered name.
It’s important to note that, although the Naming interface is a default naming service provided with RMI, the
RMI registry can be tied into other naming services by vendors. Sun has provided a binding to the RMI registry
through the Java Naming and Directory Interface(JNDI).

3.4 RMI Architecture


The RMI system consists of three layers: the stub/skeleton layer, the remote reference layer, and the transport
layer. The boundary at each layer is defined by a specific interface and protocol; each layer, therefore, is inde-
pendent of the next and can be replaced by an alternate implementation without affecting the other layers in the
system. For example, the current transport implementation is TCP-based (using Java sockets), but a transport
based on UDP could be substituted.
To accomplish transparent transmission of objects from one address space to another, the technique of object
serialization (designed specifically for the Java language) is used. Object serialization is described in this chapter
only with regard to its use for marshaling primitives and objects.
Now that we’ve seen a complete example of an RMI object in action, let’s look at what makes remote objects
work, starting with an overview of the underlying RMI architecture. There are three layers that comprise the
basic remote-object communication facilities in RMI:
• The stub/skeleton layer, which provides the interface that client and server application objects use to
interact with each other.
• The remote reference layer, which is the middleware between the stub/skeleton layer and the underlying
transport protocol. This layer handles the creation and management of remote object references.

• The transport protocol layer, which is the binary data protocol that sends remote object requests over the
wire.
These layers interact with each other as shown in Figure 3.4. In this figure, the server is the application that
provides remotely accessible objects, while the client is any remote application that communicates with these
server objects. As you can see in Figure 3.4, a client makes a request of a remote object using a client-side stub;

Figure 3.4: The RMI runtime architecture

the server object receives this request from a server-side object skeleton. A client initiates a remote method
invocation by calling a method on a stub object. The stub maintains an internal reference to the remote object

CHAPTER 3. REMOTE METHOD INVOCATION 40


Advance Java Sumit A. Khatri

it represents and forwards the method invocation request through the remote reference layer by marshalling the
method arguments into serialized form and asking the remote reference layer to forward the method request and
arguments to the appropriate remote object. Marshalling involves converting local objects into portable form
so that they can be transmitted to a remote process. Each object is checked as it is marshaled, to determine
whether it implements the java.rmi.Remote interface. If it does, its remote reference is used as its marshaled
data. If it isn’t a Remote object, the argument is serialized into bytes that are sent to the remote host and
reconstituted into a copy of the local object. If the argument is neither Remote nor Serializable, the stub throws
a java.rmi.MarshalException back to the client.
If the marshalling of method arguments succeeds, the client-side remote reference layer receives the remote
reference and marshaled arguments from the stub. This layer converts the client request into low-level RMI
transport requests according to the type of remote object communication being used. In RMI, remote objects can
(potentially) run under several different communication styles, such as point-to-point object references, replicated
objects, or multicast objects. The remote reference layer is responsible for knowing which communication style
is in effect for a given remote object and generating the corresponding transport-level requests. In the current
version of RMI (Version 1.2 of Java 2), the only communication style provided out of the box is point-to-point
object references, so this is the only style we’ll discuss in this chapter. For a point-to-point communication, the
remote reference layer constructs a single network-level request and sends it over the wire to the sole remote
object that corresponds to the remote reference passed along with the request.
On the server, the server-side remote reference layer receives the transport-level request and converts it into a
request for the server skeleton that matches the referenced object. The skeleton converts the remote request into
the appropriate method call on the actual server object, which involves unmarshalling the method arguments into
the server environment and passing them to the server object. As you might expect, unmarshalling is the inverse
procedure to the marshalling process on the client. Arguments sent as remote references are converted into local
stubs on the server, and arguments sent as serialized objects are converted into local copies of the originals.
If the method call generates a return value or an exception, the skeleton marshals the object for transport
back to the client and forwards it through the server reference layer. This result is sent back using the appropriate
transport protocol, where it passes through the client reference layer and stub, is unmarshaled by the stub, and
is finally handed back to the client thread that invoked the remote method.

3.4.1 The Stub/Skeleton Layer


The stub/skeleton layer is the interface between the application layer and the rest of the RMI system. This layer
does not deal with specifics of any transport, but transmits data to the remote reference layer via the abstraction
of marshal streams. Marshal streams employ a mechanism called object serialization which enables Java objects
to be transmitted between address spaces. Objects transmitted using the object serialization system are passed
by copy to the remote address space, unless they are remote objects, in which case they are passed by reference.
A stub for a remote object is the client-side proxy for the remote object. Such a stub implements all the
interfaces that are supported by the remote object implementation. A client-side stub is responsible for:
• Initiating a call to the remote object (by calling the remote reference layer).
• Marshaling arguments to a marshal stream (obtained from the remote reference layer).
• Informing the remote reference layer that the call should be invoked.
• Unmarshaling the return value or exception from a marshal stream.
• Informing the remote reference layer that the call is complete.
A skeleton for a remote object is a server-side entity that contains a method which dispatches calls to the actual
remote object implementation. The skeleton is responsible for:
• Unmarshaling arguments from the marshal stream.
• Making the up-call to the actual remote object implementation.
• Marshaling the return value of the call or an exception (if one occurred) onto the marshal stream.

3.4.2 The Remote Reference Layer


The remote reference layer deals with the lower-level transport interface. This layer is also responsible for carrying
out a specific remote reference protocol which is independent of the client stubs and server skeletons. Each remote
object implementation chooses its own remote reference subclass that operates on its behalf. Various invocation
protocols can be carried out at this layer. Examples are:

CHAPTER 3. REMOTE METHOD INVOCATION 41


Advance Java Sumit A. Khatri

• Unicast point-to-point invocation.


• Invocation to replicated object groups.
• Support for a specific replication strategy.

• Support for a persistent reference to the remote object (enabling activation of the remote object).
• Reconnection strategies (if remote object becomes inaccessible).

3.4.3 The Transport Layer


In general, the transport layer of the RMI system is responsible for:
• Setting up connections to remote address spaces.
• Managing connections.

• Monitoring connection liveness.


• Listening for incoming calls.
• Maintaining a table of remote objects that reside in the address space.
• Setting up a connection for an incoming call.

• Locating the dispatcher for the target of the remote call and passing the connection to this dispatcher.
The concrete representation of a remote object reference consists of an endpoint and an object identifier. This
representation is called a live reference. Given a live reference for a remote object, a transport can use the
endpoint to set up a connection to the address space in which the remote object resides. On the server side, the
transport uses the object identifier to look up the target of the remote call. The transport for the RMI system
consists of four basic abstractions:
• An endpoint is the abstraction used to denote an address space or Java virtual machine. In the implementa-
tion, an endpoint can be mapped to its transport. That is, given an endpoint, a specific transport instance
can be obtained.

• A channel is the abstraction for a conduit between two address spaces. As such, it is responsible for managing
connections between the local address space and the remote address space for which it is a channel.
• A connection is the abstraction for transferring data (performing input/output).
• The transport abstraction manages channels. Each channel is a virtual connection between two address
spaces. Within a transport, only one channel exists per pair of address spaces (the local address space and a
remote address space). Given an endpoint to a remote address space, a transport sets up a channel to that
address space. The transport abstraction is also responsible for accepting calls on incoming connections to
the address space, setting up a connection object for the call, and dispatching to higher layers in the system.

3.5 Defining Remote Objects


Now that you have a basic idea of how Java RMI works, we can explore the details of creating and using distributed
objects with RMI. As I mentioned earlier, defining a remote RMI object involves specifying a remote interface for
the object, then providing a class that implements this interface. The remote interface and implementation class
are then used by RMI to generate a client stub and server skeleton for your remote object. The communication
between local objects and remote objects is handled using these client stubs and server skeletons. The relationships
among stubs, skeletons, and the objects that use them are shown in Figure 3.5. When a client gets a reference to
a remote object and then calls methods on this object reference, there needs to be a way for the method request
to get transmitted back to the actual object on the remote server and for the results of the method call to get
transmitted back to the client. This is what the generated stub and skeleton classes are for. They act as the
communication link between the client and your exported remote object, making it seem to the client that the
object actually exists within its Java VM.
The RMI compiler (rmic) automatically generates these stub and skeleton classes for you. Based on the
remote interface and implementation class you provide, rmic generates stub and skeleton classes that implement
the remote interface and act as go-betweens for the client application and the actual server object. For the

CHAPTER 3. REMOTE METHOD INVOCATION 42


Advance Java Sumit A. Khatri

Figure 3.5: Relationships among remote object, stub, and skeleton classes

client stub class, the compiler generates an implementation of each remote method that simply packages up
(marshals) the method arguments and transmits them to the server. For the server skeleton class, the RMI
compiler generates another set of implementations of the remote methods, but these are designed to receive the
method arguments from the remote method call, unpackage them, and make the corresponding method call on
the object implementation. Whatever the method call generates (return data or an exception), the results are
packaged and transmitted back to the remote client. The client stub method (which is still executing at this
point) unpackages the results and delivers them to the client as the result of its remote method call.

3.6 Creating A Remote Service


Ok now we have a general background on RMI lets go into more details of creating a remote service. We can
break down the creation of a remote service where we communicate locally with remote objects into a number of
steps:
1. Create a remote interface that extends the java.rmi.Remote interface and includes any methods we want
our clients to call remotely.

2. Implement our remote interface methods


3. Run RMIC on the remote implementation.
4. Start the remote registry.
5. Start the remote service.

We will now go through each step in the process writing the interfaces and classes required as we go.

3.6.1 Create a Remote Interface


The first step in the process is very straightforward as all we need to do is create an interface for the methods we
require for our remote service. Below is code showing how we do this.
1 im po rt j a v a . rmi . Remote ; // Our Remote marker i n t e r f a c e
2 im po rt j a v a . rmi . RemoteException ; // An e x c e p t i o n we need
3
4 p u b l i c i n t e r f a c e R e m o t e S e r v i c e e x t e n d s Remote
5 {
6 p u b l i c S t r i n g remoteMethod ( ) throws RemoteException ;
7 }
Listing 3.5: Creating Remote Interface

The following command shows compiling the RemoteService interface. We extend the Remote marker interface
and then add any methods needed for our remote service. In this case we are just adding the remoteMethod()
which throws a RemoteException exception.
javac RemoteService.java

CHAPTER 3. REMOTE METHOD INVOCATION 43


Advance Java Sumit A. Khatri

3.6.2 Implement The Remote Interface


This is the real workhorse on the remote service side where we implement our remote interface, its methods and
extend the UnicastRemoteObject for communicating with the remote object.
1 im po rt j a v a . rmi . Naming ; // Remote o b j e c t r e f e r e n c e s t o r a g e and r e t r i e v a l
2 im po rt j a v a . rmi . Remote ; // Remote i n t e r f a c e
3 im po rt j a v a . rmi . RemoteException ; // Remote e x c e p t i o n
4 im po rt j a v a . rmi . s e r v e r . UnicastRemoteObject ; // Remote o b j e c t communication
5
6 p u b l i c c l a s s R e m o t e S e r v i c e I m p l e x t e n d s UnicastRemoteObject implements R e m o t e S e r v i c e {
7
8 // C o n s t r u c t o r
9 p u b l i c R e m o t e S e r v i c e I m p l ( ) throws RemoteException { }
10
11 // The implemented remote method we w i l l c a l l
12 p u b l i c S t r i n g remoteMethod ( ) throws RemoteException {
13 r e t u r n ”We communicated with t h e remote s e r v e r method ! ! ” ;
14 }
15
16 // C r e a t e a remote o b j e c t and bind i t t o t h e RMI r e g i s t r y
17 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
18 try {
19 R e m o t e S e r v i c e s e r v i c e = new R e m o t e S e r v i c e I m p l ( ) ;
20 Naming . r e b i n d ( ” rmi : / / l o c a l h o s t : 1 0 9 9 / RemoteMethod” , s e r v i c e ) ;
21 } catch ( Exception e ) {
22 System . out . p r i n t l n ( ”An e x c e p t i o n o c c u r r e d w i t h i n t h e remote s e r v i c e . ” + e ) ;
23 }
24 }
25 }
Listing 3.6: Implementing Remote Interface

The following command shows compiling the RemoteServiceImpl class. We are just implementing the re-
moteMethod() which throws a RemoteException exception. Within the main() method we try to create a remote
object and bind it to the RMI registry using the java.rmi.Naming class, which is used for storing and obtaining
references to remote objects in a remote object registry. The name we have used ”RemoteMethod” is used on the
client side to access the Registry via the Naming.lookup() method.
javac RemoteServiceImpl.java

3.6.3 Run rmic on remote implementation


The rmic compiler generates stub and skeleton class files (JRMP protocol) and stub and tie class files (IIOP
protocol) for remote objects. These classes files are generated from compiled Java programming language classes
that are remote object implementation classes. A remote implementation class is a class that implements the
interface java.rmi.Remote. The class names in the rmic command must be for classes that have been compiled
successfully with the javac command and must be fully package qualified. For example, running rmic on the class
file name RemoteServiceImpl as shown here:
rmic RemoteServiceImpl

3.6.4 Starting The Remote Registry


This is a fairly strighforward step as we are starting the RMI registry maually, in the real world we would need
to communicate with the RMI registry programmatically. The command below shows the command to start the
RMI registry.
rmiregistry &

3.6.5 Starting The Remote Service


Now we need to start the remote service implementation class, which in our case is the RemoteServiceImpl class.
We will do this from another terminal so the registry keep running.
The following command shows the results of running the RemoteServiceImpl class. The RMI server side is
now all set up ready to communicate with clients via our remote object stub.
java RemoteServiceImpl

CHAPTER 3. REMOTE METHOD INVOCATION 44


Advance Java Sumit A. Khatri

3.6.6 Creating A Client


On the client side, each client needs to have a copy of the client code. Following is the code our clients require to
access the remoteMethod() method on the server. We will do this from another terminal so the registry and our
remote server are kept running on the other two. We use the Naming.lookup() method to get our remote object
stub on the registry, which returns an Object object, hence the cast. We are using localhost as our URL and the
same RemoteMethod name that we used to register our service. Using the returned registry information we call
the remoteMethod() method on the server and print the results.
As a point of interest we do not need to serialize the String object of the remoteMethod() method on the
client or server side which gets passed across the network as, like many classes in the API, it is already serialized.
1 im po rt j a v a . rmi . Naming ; // Remote o b j e c t r e f e r e n c e s t o r a g e and r e t r i e v a l
2
3 p u b l i c c l a s s RemoteClient {
4
5 p u b l i c s t a t i c v o i d main ( S t r i n g [ ] a r g s ) {
6 new RemoteClient ( ) . s t a r t ( ) ;
7 }
8
9 public s t a t i c void s t a r t ( ) {
10 try {
11 // Look up our remote s t u b on RMI r e g i s t r y
12 R e m o t e S e r v i c e s e r v i c e = ( R e m o t e S e r v i c e ) Naming . l o o k u p ( ” rmi : / / l o c a l h o s t /RemoteMethod”
);
13 // C a l l remote method now we have a l o o k u p
14 S t r i n g s t r = s e r v i c e . remoteMethod ( ) ;
15 System . out . p r i n t l n ( s t r ) ;
16 } catch ( Exception e ) {
17 System . out . p r i n t l n ( ”An e x c e p t i o n o c c u r r e d w i t h i n t h e c l i e n t ’ s remote s e r v i c e . ” + e )
;
18 }
19 }
20 }
Listing 3.7: Creating Client

The following Figure 3.6 shows the results of compiling and running the RemoteClient class. As you can see we
are getting the returned string from the remoteMethod() method held on the server and printing it out on the
client.

Figure 3.6: Rsults of compiling and running RemoteClient class

3.7 References
• https://docs.oracle.com/javase/9/docs/specs/rmi/index.html
• http://server2client.com/java6swing/rmi.html
• http://ftp.icm.edu.pl/packages/javasoft-docs/jdk1.1/rmi-spec.pdf

CHAPTER 3. REMOTE METHOD INVOCATION 45

You might also like