[Go to site: main page, start]

0% found this document useful (0 votes)
2 views45 pages

Advanced Java Programming

The document provides an overview of advanced Java programming concepts, including object-oriented programming, GUI design, multithreading, and network programming. It outlines Java coding standards for identifiers, reserved words, variable scope, and data types, as well as event handling mechanisms and the thread model. Additionally, it discusses the creation and management of threads, emphasizing the importance of multithreading in efficient program execution.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views45 pages

Advanced Java Programming

The document provides an overview of advanced Java programming concepts, including object-oriented programming, GUI design, multithreading, and network programming. It outlines Java coding standards for identifiers, reserved words, variable scope, and data types, as well as event handling mechanisms and the thread model. Additionally, it discusses the creation and management of threads, emphasizing the importance of multithreading in efficient program execution.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

ADVANCED JAVA PROGRAMMING


 Object-oriented programming
 Graphical user interface design
 Multithreading
 Network Programming

JAVA Coding Standard

IDENTIFIERS

Should begin with a letter and may contain additional letters and digits. Identifiers are the same as
variables.

 Use descriptive names for all variables, function names, constants and other identifiers. Use single
letters only for the counter in loops.
 Variable names start with lower-case
 Multi-word identifiers are internally capitalized
 Do not use hyphens or underscores to separate multi-word identifiers.

What about the unicode set? This is the format: \uHHHH

Remember any other escape characters such as \n, \t and \\?

The following lists some of these conventions based on the type of identifier:
Class name
The first letter of each word is capitalized, examples:
Mammal, SeaMammal

Function name
The first letter of each, except the first, word is capitalized, examples:
getAge, setHeight

Variable name
The first letter of each, except the first, word is capitalized, examples:
age, brainSize
Constant names
Every letter is capitalized and underscores are used between words, examples:
MAX_HEIGHT, MAX_AGE

RESERVED WORDS
2

As you may have noticed, many of Java's keywords are borrowed from C/C++. Also, as in C/C++,
keywords are always written in lowercase. Generally speaking, Java's keywords can be categorized
according to their function as follows (examples are in parenthesis):

Data declaration keywords (boolean, float, int)


Loop keywords (continue, while, for)
Conditional keywords (if, else, switch)
Exception keywords (try, throw, catch)
Structure keywords (class, extends)
Modifier and access keywords (private, public)
Miscellaneous keywords (true, null)

The following keywords and their use.


boolean default for private switch
break double if protected this
case else import public throws
catch extends int return try
char final new static void
class float package super while

VARIABLE SCOPE

Where is it appropriate to declare a variable? Does it make a difference?

PRIMITIVE DATA TYPES

 int (16-bit)
 float (32-bit)
 double (64-bit
 boolean (true/false)
 char (16-bit unicode)

What about String?

 What about Integer, and Double?

OBJECTS

 Why object oriented programming?


 Objects need to be built, so we need constructors.
 Instance variables and the role they play when defining objects.
 What about methods of an object?

ARRAYS
3

int[] array = new int[5]; // one-dimensional array

it may also be declared as:

int[] array = {1, 2, 3, 4, 5}; // it is initialized and declared at the same time.

Arrays can be of any primitive data type or object. Arrays have an instance variable "length" that we can
access to find out how big the array is. Remember that an Array can throw an
IndexOutOfBoundsException. Make use of it to make your code safe.

VECTORS

Must import [Link].*;

Unlike arrays, vectors can only hold objects, no primitive data types are allowed. Vectors can grow big and
unbounded. You may want to specify the capacity of the vector but you don�t need to. The default
capacity is 10 and it doubles in size every time the capacity is reached.

Just like arrays have the "length" instance variable, Vectors have a .size() method that returns the current
size of the vector.

 void .addElement(Object obj)


 void .setElementAt(Object obj, int index)
 Object .elementAt(int index)
 void .insertElementAt(Object obj, int index)
 void .removeElementAt(Object obj, int index)

ENUMERATION

This is an iterator and it is very important concept in data structures for ICS211. An Enumeration lets us
visit every element of a Vector one by one.

Vector v = new Vector();


Enumeration e = [Link]();
While([Link]()){
Object o = [Link];
// we do something with each element.
}

OPERATORS AND PRECEDENCE IN JAVA

 Arithmetic operators.
 Incrementing and decrementing operators.
 Good to know but not necessary the Assignment operators
 Relational operators
 Logical operators
4

LOW CONTROL / REPETITION STATEMENTS

Must be familiar with:

 for loops
 while loops
 if statements
 switch � case statements

Event Handling in Java

An event can be defined as changing the state of an object or behavior by performing actions. Actions can
be a button click, cursor movement, keypress through keyboard or page scrolling, etc.
The [Link] package can be used to provide various event classes.
Classification of Events
 Foreground Events
 Background Events

Types of Events

1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e., foreground events are
generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are known as background events. Examples of
these events are operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen after an event occur. To
handle the events, Java follows the Delegation Event model.
Delegation Event model
 It has Sources and Listeners.
5

Delegation Event Model

 Source: Events are generated from the source. There are various sources like buttons, checkboxes,
list, menu-item, choice, scrollbar, text components, windows, etc., to generate events.
 Listeners: Listeners are used for handling the events generated from the source. Each of these
listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Registering the Source With Listener
Different Classes provide different registration methods.
Syntax:
addTypeListener()

where Type represents the type of event.


Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes in Java

Event Class Listener Interface Description


An event that indicates that a component-defined action
ActionEvent ActionListener occurred like a button click or selecting an item from the
menu-item list.
The adjustment event is emitted by an Adjustable object
AdjustmentEvent AdjustmentListener
like Scrollbar.
An event that indicates that a component moved, the size
ComponentEvent ComponentListener
changed or changed its visibility.
When a component is added to a container (or) removed
ContainerEvent ContainerListener
from it, then this event is generated by a container object.
These are focus-related events, which include focus,
FocusEvent FocusListener
focusin, focusout, and blur.
An event that indicates whether an item was selected or
ItemEvent ItemListener
not.
An event that occurs due to a sequence of keypresses on
KeyEvent KeyListener
the keyboard.
MouseListener & The events that occur due to the user interaction with the
MouseEvent
MouseMotionListener mouse (Pointing Device).
MouseWheelEven An event that specifies that the mouse wheel was rotated
MouseWheelListener
t in a component.
6

TextEvent TextListener An event that occurs when an object’s text changes.


An event which indicates whether a window has changed
WindowEvent WindowListener
its status or not.

Note: As Interfaces contains abstract methods which need to implemented by the registered class to handle
events.
Different interfaces consists of different methods which are specified below.

Listener Interface Methods


ActionListener  actionPerformed()
AdjustmentListener  adjustmentValueChanged()
 componentResized() componentShown() componentMoved()
ComponentListener
componentHidden()
ContainerListener  componentAdded() componentRemoved()
FocusListener  focusGained() focusLost()
ItemListener  itemStateChanged()
KeyListener  keyTyped() keyPressed() keyReleased()
 mousePressed() mouseClicked() mouseEntered()
MouseListener
mouseExited() mouseReleased()
MouseMotionListener  mouseMoved() mouseDragged()
MouseWheelListener  mouseWheelMoved()
TextListener  textChanged()
 windowActivated() windowDeactivated() windowOpened()
WindowListener windowClosed() windowClosing()
 windowIconified() windowDeiconified()

Flow of Event Handling


1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event generation, and it holds all
information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.
Code-Approaches
The three approaches for performing event handling are by placing the event handling code in one of the
below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class
Note: Use any IDE or install JDK to run the code, Online compiler may throw errors due to the
unavailability of some packages.
Event Handling Within Class

 Java
7

// Java program to demonstrate the


// event handling within the class

import [Link].*;
import [Link].*;

class GFGTop extends Frame implements ActionListener {

TextField textField;

GFGTop()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of the component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
[Link](100, 120, 80, 30);

// Registering component with listener


// this refers to current instance
[Link](this);

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

// implementing method of actionListener


public void actionPerformed(ActionEvent e)
{
// Setting text to field
[Link]("GFG!");
}

public static void main(String[] args)


{
new GFGTop();
}
}

Output
8

After Clicking, the text field value is set to GFG!

Explanation
1. Firstly extend the class with the applet and implement the respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event. i.e. ActionEvent by addActionListener().
4. In the end, implement the abstract method.
Event Handling by Other Class

 Java

// Java program to demonstrate the


// event handling by the other class

import [Link].*;
import [Link].*;

class GFG1 extends Frame {

TextField textField;

GFG2()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
[Link](100, 120, 80, 30);

Other other = new Other(this);

// Registering component with listener


// Passing other class as reference
[Link](other);
9

// add Components
add(textField);
add(button);

// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG2();
}
}

 Java

/// import necessary packages


import [Link].*;

// implements the listener interface


class Other implements ActionListener {

GFG2 gfgObj;

Other(GFG1 gfgObj) {
[Link] = gfgObj;
}

public void actionPerformed(ActionEvent e)


{
// setting text from different class
[Link]("Using Different Classes");
}
}

Output
10

Handling event from different class

Event Handling By Anonymous Class

 Java

// Java program to demonstrate the


// event handling by the anonymous class

import [Link].*;
import [Link].*;

class GFG3 extends Frame {

TextField textField;

GFG3()
{
// Component Creation
textField = new TextField();

// setBounds method is used to provide


// position and size of component
[Link](60, 50, 180, 25);
Button button = new Button("click Here");
[Link](100, 120, 80, 30);

// Registering component with listener anonymously


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Setting text to field
[Link]("Anonymous");
}
});

// add Components
add(textField);
add(button);
11

//make size viewable


setSize(300,300);
// set visibility
setVisible(true);
}

public static void main(String[] args)


{
new GFG3();
}
}

Output

Handling anonymously

Thread Concept in Java

Before introducing the thread concept, we were unable to run more than one task in parallel. It was a
drawback, and to remove that drawback, Thread Concept was introduced.

A Thread is a very light-weighted process, or we can say the smallest part of the process that allows a
program to operate more efficiently by running multiple tasks simultaneously.

In order to perform complicated tasks in the background, we used the Thread concept in Java. All the
tasks are executed without affecting the main program. In a program or process, all the threads have their
own separate path for execution, so each thread of a process is independent.
12

Another benefit of using thread is that if a thread gets an exception or an error at the time of its execution,
it doesn't affect the execution of the other threads. All the threads share a common memory and have their
own stack, local variables and program counter. When multiple threads are executed in parallel at the same
time, this process is known as Multithreading.

In a simple way, a Thread is a:

o Feature through which we can perform multiple activities within a single process.
o Lightweight process.
o Series of executed statements.
o Nested sequence of method calls.

Thread Model

Just like a process, a thread exists in several states. These states are as follows:

1) New (Ready to run)


A thread is in New when it gets CPU time.
2) Running
A thread is in a Running state when it is under execution.
3) Suspended

A thread is in the Suspended state when it is temporarily inactive or under execution.

4) Blocked
13

A thread is in the Blocked state when it is waiting for resources.

5) Terminated

A thread comes in this state when at any given time, it halts its execution immediately.

Creating Thread

A thread is created either by "creating or implementing" the Runnable Interface or by extending


the Thread class. These are the only two ways through which we can create a thread.

Let's dive into details of both these way of creating a thread:

Thread Class

A Thread class has several methods and constructors which allow us to perform various operations on a
thread. The Thread class extends the Object class. The Object class implements the Runnable interface.
The thread class has the following constructors that are used to perform various operations.
o Thread()
o Thread(Runnable, String name)
o Thread(Runnable target)
o Thread(ThreadGroup group, Runnable target, String name)
o Thread(ThreadGroup group, Runnable target)
o Thread(ThreadGroup group, String name)
o Thread(ThreadGroup group, Runnable target, String name, long stackSize)

Runnable Interface(run() method)

The Runnable interface is required to be implemented by that class whose instances are intended to be
executed by a thread. The runnable interface gives us the run() method to perform an action for the thread.

start() method

The method is used for starting a thread that we have newly created. It starts a new thread with a new
callstack. After executing the start() method, the thread changes the state from New to Runnable. It
executes the run() method when the thread gets the correct time to execute it.

Let's take an example to understand how we can create a Java thread by extending the Thread class:

[Link]
1. // Implementing runnable interface by extending Thread class
2. public class ThreadExample1 extends Thread {
3. // run() method to perform action for thread.
4. public void run()
14

5. {
6. int a= 10;
7. int b=12;
8. int result = a+b;
9. [Link]("Thread started running..");
10. [Link]("Sum of two numbers is: "+ result);
11. }
12. public static void main( String args[] )
13. {
14. // Creating instance of the class extend Thread class
15. ThreadExample1 t1 = new ThreadExample1();
16. //calling start method to execute the run() method of the Thread class
17. [Link]();
18. }
19. }
Output:

Creating thread by implementing the runnable interface

In Java, we can also create a thread by implementing the runnable interface. The runnable interface
provides us both the run() method and the start() method.

Let's takes an example to understand how we can create, start and run the thread using the runnable
interface.

[Link]

1. class NewThread implements Runnable {


2. String name;
3. Thread thread;
15

4. NewThread (String name){


5. [Link] = name;
6. thread = new Thread(this, name);
7. [Link]( "A New thread: " + thread+ "is created\n" );
8. [Link]();
9. }
10. public void run() {
11. try {
12. for(int j = 5; j > 0; j--) {
13. [Link](name + ": " + j);
14. [Link](1000);
15. }
16. }catch (InterruptedException e) {
17. [Link](name + " thread Interrupted");
18. }
19. [Link](name + " thread exiting.");
20. }
21. }
22. class ThreadExample2 {
23. public static void main(String args[]) {
24. new NewThread("1st");
25. new NewThread("2nd");
26. new NewThread("3rd");
27. try {
28. [Link](8000);
29. } catch (InterruptedException excetion) {
30. [Link]("Inturruption occurs in Main Thread");
31. }
32. [Link]("We are exiting from Main Thread");
33. }
34. }

Output:
16

Java Networking
When computing devices such as laptops, desktops, servers, smartphones,
and tablets and an eternally-expanding arrangement of IoT gadgets such as
cameras, door locks, doorbells, refrigerators, audio/visual systems,
thermostats, and various sensors are sharing information and data with each
other is known as networking.

In simple words, the term network programming or networking associates with


writing programs that can be executed over various computer devices, in
which all the devices are connected to each other to share resources using a
network.

What is Java Networking?

Networking supplements a lot of power to simple programs. With networks, a


single program can regain information stored in millions of computers
positioned anywhere in the world. Java is the leading programming language
composed from scratch with networking in mind. Java Networking is a notion
of combining two or more computing devices together to share resources.
17

All the Java program communications over the network are done at the
application layer. The [Link] package of the J2SE APIs comprises various
classes and interfaces that execute the low-level communication features,
enabling the user to formulate programs that focus on resolving the problem.

Common Network Protocols

As stated earlier, the [Link] package of the Java programming language


includes various classes and interfaces that provide an easy-to-use means to
access network resources. Other than classes and interfaces,
the [Link] package also provides support for the two well-known network
protocols. These are:
1. Transmission Control Protocol (TCP) – TCP or Transmission Control
Protocol allows secure communication between different applications. TCP
is a connection-oriented protocol which means that once a connection is
established, data can be transmitted in two directions. This protocol is
typically used over the Internet Protocol. Therefore, TCP is also referred to
as TCP/IP. TCP has built-in methods to examine for errors and ensure the
delivery of data in the order it was sent, making it a complete protocol for
transporting information like still images, data files, and web pages.

2. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a


connection-less protocol that allows data packets to be transmitted
between different applications. UDP is a simpler Internet protocol in which
error-checking and recovery services are not required. In UDP, there is no
overhead for opening a connection, maintaining a connection, or
terminating a connection. In UDP, the data is continuously sent to the
recipient, whether they receive it or not.

Java Networking Terminology

In Java Networking, many terminologies are used frequently. These widely


used Java Networking Terminologies are given as follows:
1. IP Address – An IP address is a unique address that distinguishes a device
on the internet or a local network. IP stands for “Internet Protocol.” It
comprises a set of rules governing the format of data sent via the internet
or local network. IP Address is referred to as a logical address that can be
modified. It is composed of octets. The range of each octet varies from 0 to
255.
 Range of the IP Address – [Link] to [Link]
 For Example – [Link]
18

2. Port Number – A port number is a method to recognize a particular


process connecting internet or other network information when it reaches a
server. The port number is used to identify different applications uniquely.
The port number behaves as a communication endpoint among
applications. The port number is correlated with the IP address for
transmission and communication among two applications. There are 65,535
port numbers, but not all are used every day.

3. Protocol – A network protocol is an organized set of commands that define


how data is transmitted between different devices in the same network.
Network protocols are the reason through which a user can easily
communicate with people all over the world and thus play a critical role in
modern digital communications. For Example – TCP, FTP, POP, etc.

4. MAC Address – MAC address stands for Media Access Control address. It is
a bizarre identifier that is allocated to a NIC (Network Interface Controller/
Card). It contains a 48 bit or 64-bit address, which is combined with the
network adapter. MAC address can be in hexadecimal composition. In
simple words, a MAC address is a unique number that is used to track a
device in a network.

5. Socket – A socket is one endpoint of a two-way communication connection


between the two applications running on the network. The socket
mechanism presents a method of inter-process communication (IPC) by
setting named contact points between which the communication occurs. A
socket is tied to a port number so that the TCP layer can recognize the
application to which the data is intended to be sent.

6. Connection-oriented and connection-less protocol – In a connection-


oriented service, the user must establish a connection before starting the
communication. When the connection is established, the user can send the
message or the information, and after this, they can release the connection.
However, In connectionless protocol, the data is transported in one route
from source to destination without verifying that the destination is still
there or not or if it is ready to receive the message. Authentication is not
needed in the connectionless protocol.
 Example of Connection-oriented Protocol – Transmission Control Protocol
(TCP)
 Example of Connectionless Protocol – User Datagram Protocol (UDP)

Java networking classes

The [Link] package of the Java programming language includes various


classes that provide an easy-to-use means to access network resources. The
19

classes covered in the [Link] package are given as follows –

 Cache Request – The CacheRequest class is used in java whenever there is a need to store
resources in ResponseCache. The objects of this class provide an edge for the OutputStream
object to store resource data into the cache.

 Cookie Handler – The CookieHandler class is used in Java to implement a callback


mechanism for securing up an HTTP state management policy implementation inside the
HTTP protocol handler. The HTTP state management mechanism specifies the mechanism
of how to make HTTP requests and responses.

 CookieManager – The CookieManager class is used to provide a precise implementation


of CookieHandler. This class separates the storage of cookies from the policy surrounding
accepting and rejecting cookies. A CookieManager comprises a CookieStore and a
CookiePolicy.

 DatagramPacket – The DatagramPacket class is used to provide a facility for the


connectionless transfer of messages from one system to another. This class provides tools
for the production of datagram packets for connectionless transmission by applying the
datagram socket class.

 InetAddress – The InetAddress class is used to provide methods to get the IP address of
any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.

 Server Socket – The ServerSocket class is used for implementing system-independent


implementation of the server-side of a client/server Socket Connection. The constructor
for ServerSocket class throws an exception if it can’t listen on the specified port. For
example – it will throw an exception if the port is already being used.

 Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations. The users can implement various
networking actions such as sending, reading data, and closing connections. Each Socket
object built using [Link] class has been connected exactly with 1 remote host;
for connecting to another host, a user must create a new socket object.

 DatagramSocket – The DatagramSocket class is a network socket that provides a


connection-less point for sending and receiving packets. Every packet sent from a
datagram socket is individually routed and delivered. It can further be practiced for
transmitting and accepting broadcast information. Datagram Sockets is Java’s mechanism
for providing network communication via UDP instead of TCP.

 Proxy – A proxy is a changeless object and a kind of tool or method or program or


system, which serves to preserve the data of its users and computers. It behaves like a wall
between computers and internet users. A Proxy Object represents the Proxy settings to be
20

applied with a connection.

 URL – The URL class in Java is the entry point to any available sources on the internet. A
Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on the
World Wide Web. A source can denote a simple file or directory, or it can indicate a more
difficult object, such as a query to a database or a search engine.

 URLConnection – The URLConnection class in Java is an abstract class describing a


connection of a resource as defined by a similar URL. The URLConnection class is used
for assisting two distinct yet interrelated purposes. Firstly it provides control on
interaction with a server(especially an HTTP server) than a URL class. Furthermore, with
a URLConnection, a user can verify the header transferred by the server and can react
consequently. A user can also configure header fields used in client requests using
URLConnection.

Java Networking Interfaces

The [Link] package of the Java programming language includes various interfaces also that
provide an easy-to-use means to access network resources. The interfaces included in
the [Link] package are as follows:
1. CookiePolicy – The CookiePolicy interface in the [Link] package provides the classes for
implementing various networking applications. It decides which cookies should be accepted
and which should be rejected. In CookiePolicy, there are three pre-defined policy
implementations, namely ACCEPT_ALL, ACCEPT_NONE, and
ACCEPT_ORIGINAL_SERVER.

2. CookieStore – A CookieStore is an interface that describes a storage space for cookies.


CookieManager combines the cookies to the CookieStore for each HTTP response and
recovers cookies from the CookieStore for each HTTP request.

3. FileNameMap – The FileNameMap interface is an uncomplicated interface that implements


a tool to outline a file name and a MIME type string. FileNameMap charges a filename map
( known as a mimetable) from a data file.

4. SocketOption – The SocketOption interface helps the users to control the behavior of
sockets. Often, it is essential to develop necessary features in Sockets. SocketOptions allows
the user to set various standard options.

5. SocketImplFactory – The SocketImplFactory interface defines a factory for SocketImpl


instances. It is used by the socket class to create socket implementations that implement
various policies.
21

6. ProtocolFamily – This interface represents a family of communication protocols. The


ProtocolFamily interface contains a method known as name(), which returns the name of the
protocol family.

Socket Programming

Java Socket programming is practiced for communication between the applications working on
different JRE. Sockets implement the communication tool between two computers using TCP.
Java Socket programming can either be connection-oriented or connection-less. In Socket
Programming, Socket and ServerSocket classes are managed for connection-oriented socket
programming. However, DatagramSocket and DatagramPacket classes are utilized for
connection-less socket programming.
A client application generates a socket on its end of the communication and strives to combine
that socket with a server. When the connection is established, the server generates an object of
socket class on its communication end. The client and the server can now communicate by
writing to and reading from the socket.
The [Link] class describes a socket, and the [Link] class implements a
tool for the server program to host clients and build connections with them.

Steps to establishing a TCP connection between two computing devices using Socket
Programming
The following are the steps that occur on establishing a TCP connection between two computers
using socket programming are given as follows:

Step 1 – The server instantiates a ServerSocket object, indicating at which port number
communication will occur.
Step 2 – After instantiating the ServerSocket object, the server requests the accept() method of
the ServerSocket class. This program pauses until a client connects to the server on the given
port.
Step 3 – After the server is idling, a client instantiates an object of Socket class, defining the
server name and the port number to connect to.
Step 4 – After the above step, the constructor of the Socket class strives to connect the client to
the designated server and the port number. If communication is authenticated, the client
forthwith has a Socket object proficient in interacting with the server.
Step 5 – On the server-side, the accept() method returns a reference to a new socket on the server
connected to the client’s socket.
After the connections are stabilized, communication can happen using I/O streams. Each object
of a socket class has both an OutputStream and an InputStream. The client’s OutputStream is
correlated to the server’s InputStream, and the client’s InputStream is combined with the server’s
OutputStream. Transmission Control Protocol (TCP) is a two-way communication protocol.
Hence information can be transmitted over both streams at the corresponding time.

Socket Class
22

The Socket class is used to create socket objects that help the users in implementing all
fundamental socket operations. The users can implement various networking actions such as
sending, reading data, and closing connections. Each Socket object created
using [Link] class has been correlated specifically with 1 remote host. If a user wants to
connect to another host, then he must build a new socket object.
Methods of Socket Class
In Socket programming, both the client and the server have a Socket object, so all the methods
under the Socket class can be invoked by both the client and the server. There are many methods
in the Socket class.

ServerSocket Class

S
Method Description
No.
public void This method is used to connect the socket to the particularized
1 connect(SocketAddres host. This method is required only when the user instantiates the
s host, int timeout) Socket applying the no-argument constructor.
This method is used to return the port to which the socket is
2 public int getPort()
pinned on the remote machine.
public InetAddress This method is used to return the location of the other computer
3
getInetAddress() to which the socket is connected.
public int This method is used to return the port to which the socket is
4
getLocalPort() joined on the local machine.
public SocketAddress
5 getRemoteSocketAddr This method returns the location of the remote socket.
ess()
This method is used to return the input stream of the socket.
public InputStream
6 This input stream is combined with the output stream of the
getInputStream()
remote socket.
This method is used to return the output stream of the socket.
public OutputStream
7 The output stream is combined with the input stream of the
getOutputStream()
remote socket.
This method is used to close the socket, which causes the object
8 public void close() of the Socket class to no longer be able to connect again to any
server.

The ServerSocket class is used for providing system-independent implementation of the server-
side of a client/server Socket Connection. The constructor for ServerSocket class throws an
exception if it can’t listen on the specified port. For example – it will throw an exception if the
port is already being used.
Methods of ServerSocket Class:
23

There are many methods in the ServerSocket class which are very useful for the users. These
methods are:

S Method Description
no.

This method is used to return the port that the server socket is
monitoring on. This method is beneficial if a user passed 0 as the
public int port number in a constructor and lets the server find a port for
getLocalPort() him.
1

public void This method is used to set the time-out value for the time in
setSoTimeout( which the server socket pauses for a client during the accept()
int timeout) method.
2

This method waits for an incoming client. This method is blocked


till either a client combines to the server on the specified port or
the socket times out, considering that the time-out value has been
public Socket set using the setSoTimeout() method. Otherwise, this method will
accept() be blocked indefinitely.
3

public void This method is used to bind the socket to the particularized
bind(SocketAd server and port in the object of SocketAddress. The user should
dress host, int use this method if he has instantiated the ServerSocket using the
backlog) no-argument constructor.
4
Example of Socket Programming in Java:
The below example illustrates a pretty basic one-way Client and Server setup where a Client
connects, sends messages to the server and the server shows them using a socket connection.
Client-Side Java Implementation:
 Java
// A Java program for a ClientSide

import [Link].*;
import [Link].*;

public class clientSide {

// initialize socket and input output streams


private Socket socket = null;
24

private DataInputStream input = null;


private DataOutputStream out = null;

// constructor to put ip address and port


public clientSide(String address, int port)
{

// establish a connection
try {

socket = new Socket(address, port);

[Link]("Connected");

// takes input from terminal


input = new DataInputStream([Link]);
// sends output to the socket
out = new DataOutputStream(
[Link]());
}
catch (UnknownHostException u) {
[Link](u);
}
catch (IOException i) {
[Link](i);
}
// string to read message from input
String line = "";
// keep reading until "End" is input
while (![Link]("End")) {
try {
line = [Link]();
[Link](line);
}
catch (IOException i) {
[Link](i);
}
}
// close the connection
try {
[Link]();
[Link]();
[Link]();
}
catch (IOException i) {
[Link](i);
}
}
public static void main(String[] args)
{
25

clientSide client
= new clientSide("[Link]", 5000);
}
}

Server Side Java Implementation:


 Java
// A Java program for a serverSide
import [Link].*;
import [Link].*;
public class serverSide {
// initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public serverSide(int port)
{

// starts server and waits for a connection


try {
server = new ServerSocket(port);

[Link]("Server started");
[Link]("Waiting for a client ...");
socket = [Link]();
[Link]("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(
[Link]()));
String line = "";
// reads message from client until "End" is sent
while (![Link]("End")) {
try {
line = [Link]();
[Link](line);
}
catch (IOException i) {
[Link](i);
}
}
[Link]("Closing connection");
// close connection
[Link]();
[Link]();
}
catch (IOException i) {
[Link](i);
26

}
}
public static void main(String[] args)
{
serverSide server = new serverSide(5000);
}
}

To run on Terminal or Command Prompt


Open two windows one for Server and another for Client.
1. First run the Server application. It will show –
Server started
Waiting for a client …
2. Then run the Client application on another terminal. It will show:
Connected
and the server accepts the client and shows,
Client accepted
3. Then you can start typing messages in the Client window. Here is the sample video of the
output0:46

InetAddress

The InetAddress class is used to provide methods to get the IP address of any hostname. An IP
address is expressed by 32-bit or 128-bit unsigned number. An object of InetAddress describes
the IP address with its analogous hostname. InetAddress can control both IPv4 and IPv6
addresses.
There are two different types of addresses:
 Unicast – It is an identifier for a single interface.
 Multicast – It is an identifier for a collection of interfaces.
Methods of InetAddress Class
Java InetAddress class represents an IP address. The following given are the important methods
of the InetAddress class –

Method Description
S No.
static InetAddress This method is used to return an object of the InetAddress class
1
getByAddress(byte[] addr) provided the raw IP address.
static InetAddress
This method is used to create an InetAddress based on the given
2 getByAddress(String host, byte[]
hostname and IP address.
addr)
static InetAddress This method is used to determine the IP address of a host when the
3
getByName(String host) host’s name is given.
static InetAddress InetAddress
4 This method is used to return the localhost.
getLocalHost()
27

5 String getHostName() This method is used to get the name of the IP address.
This method returns the IP address in the form of a string in a textual
6 String getHostAddress()
display.
7 String toString() This method is used to convert the IP address to a string.

Examples of Inet Address Class Methods:


The Java implementation of the Inet Address class to illustrate the usage of methods is shown
below:

Example 1:Java
import [Link].*;

public class InetAddressExample1 {

public static void main(String[] args) throws UnknownHostException{

// To get and print InetAddress of the Local Host


InetAddress address = [Link]();

[Link]("InetAddress of the Local Host : "+address);

// To get and print host name of the Local Host


String hostName=[Link]();

[Link]("\nHost name of the Local Host : "+hostName); }


}
Output
InetAddress of the Local Host : localhost/[Link]

Host name of the Local Host : localhost


Example 2:
import [Link].*;

public class InetAddressExample2 {

public static void main(String[] args)

throws UnknownHostException

// To get and print InetAddress of Named Hosts

InetAddress address1 = [Link](

"[Link]");

[Link]("Inet Address of named hosts : "


28

+ address1);

// To get and print ALL InetAddress of Named Host

InetAddress arr[] = [Link](

"[Link]");

[Link]("\nInet Address of ALL named hosts :");

for (int i = 0; i < [Link]; i++) {

[Link](arr[i]); } } }

Output

URL Class

The URL class in Java is the entry point to any available sources on the internet. A Class URL
describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide
Web. A source can denote a simple file or directory, or it can indicate a more difficult object,
such as a query to a database or a search engine. URL is a string of text that recognizes all the
sources on the Internet, showing us the address of the source, how to interact with it, and recover
something from it.

Components of a URL
A URL can have many forms. The most general however follows a three-components system-
29

1. Protocol – The protocol in a URL defines how information is transported among the host and
a client (or web browser).
2. Hostname – The hostname is the name of the device on which the resource exists.
3. File Name – The filename is the pathname to the file on the device.
4. Port Number – The port number is used to identify different applications uniquely. It is
typically optional.
Methods of Java URL Class
There are many methods in Java URL Class that are commonly used in Java Networking. These
methods are:

S.
No. Methods Description
public String
1 This method returns the protocol that is used by the URL.
getProtocol()
public String This method returns the hostname of the URL in IPv6
2
getHost() composition.
public int This method returns the port associated with the protocol
3
getPort() specified by the URL.
public String
4 This method returns the filename.
getFile()
public String
5 This method returns the path of the URL, or null if empty.
getPath()
public String This method is used to return the string representation of the
6
toString() provided URL object.
public int
7 This method returns the default port used.
getDefaultPort()
Examples of URL Class Methods
The Java implementation of the URL class to illustrate the usage of methods is shown below
Example 1:
 Java

import [Link].*;

public class URLclassExample1 {

public static void main(String[] args)


throws MalformedURLException
{

// creates a URL with string representation.


URL url = new URL(
"[Link]

// print the string representation of the URL


String s = [Link]();
30

[Link]("URL :" + s);


}
}

Output
URL :[Link]
Example 2:
 Java
import [Link].*;

public class URLclassExample2 {

public static void main(String[] args)


throws MalformedURLException
{

URL url = new URL(


"[Link]

// to get and print the protocol of the URL


String protocol = [Link]();

[Link]("Protocol : " + protocol);

// to get and print the hostName of the URL


String host = [Link]();

[Link]("HostName : " + host);

// to get and print the file name of the URL


String fileName = [Link]();

[Link]("File Name : " + fileName);


}
}

Output
Protocol : https
HostName : [Link]
File Name : /post/3038131
Example 3:
 Java
import [Link].*;

public class URLclassExample3 {

public static void main(String[] args)


31

throws MalformedURLException
{

URL url = new URL(


"[Link]

// to get and print the default port of the URL


int defaultPort = [Link]();

[Link]("Default Port : " + defaultPort);

// to get and print the path of the URL


String path = [Link]();

[Link]("Path : " + path);


}
}

Output
Default Port : 443
Path : /post/3038131
This was a brief introduction to Java Networking. In this article, many important topics like
Introduction of Java Networking, Common Network Protocols, Java Network Terminology, Java
Networking Classes, Java Networking Interfaces, Socket Programming, Inet Address, and URL
Class were covered.

UNIT II

Remote Method Invocation in Java




Remote Method Invocation (RMI) is an API that allows an object to invoke a method on an object
that exists in another address space, which could be on the same machine or on a remote machine.
Through RMI, an object running in a JVM present on a computer (Client-side) can invoke methods
on an object present in another JVM (Server-side). RMI creates a public remote server object that
enables client and server-side communications through simple method calls on the server object.
Stub Object: The stub object on the client machine builds an information block and sends this
information to the server.
The block consists of
 An identifier of the remote object to be used
 Method name which is to be invoked
32

 Parameters to the remote JVM


Skeleton Object: The skeleton object passes the request from the stub object to the remote object.
It performs the following tasks
 It calls the desired method on the real object present on the server.
 It forwards the parameters received from the stub object to the method.
Working of RMI
The communication between client and server is handled by using two intermediate objects: Stub
object (on client side) and Skeleton object (on server-side) as also can be depicted from below
media as follows:

These are the steps to be followed sequentially to implement Interface as defined below as
follows:
1. Defining a remote interface
2. Implementing the remote interface
3. Creating Stub and Skeleton objects from the implementation class using rmic (RMI compiler)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
Step 1: Defining the remote interface
The first thing to do is to create an interface that will provide the description of the methods that
can be invoked by remote clients. This interface should extend the Remote interface and the
method prototype within the interface should throw the RemoteException.
Example:
 Java

// Creating a Search interface


import [Link].*;
33

public interface Search extends Remote


{
// Declaring the method prototype
public String query(String search) throws RemoteException;
}

Step 2: Implementing the remote interface


The next step is to implement the remote interface. To implement the remote interface, the class
should extend to UnicastRemoteObject class of [Link] package. Also, a default constructor needs
to be created to throw the [Link] from its parent constructor in class.
 Java

// Java program to implement the Search interface


import [Link].*;
import [Link].*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();
}

// Implementation of the query interface


public String query(String search)
throws RemoteException
{
String result;
if ([Link]("Reflection in Java"))
result = "Found";
else
result = "Not Found";

return result;
}
}

Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton objects. Its
prototype is rmic classname. For above program the following command need to be executed at the
command prompt
rmic SearchQuery.
Step 4: Start the rmiregistry
Start the registry service by issuing the following command at the command prompt start
rmiregistry
Step 5: Create and execute the server application program
The next step is to create the server application program and execute it on a separate command
prompt.
34

 The server program uses createRegistry method of LocateRegistry class to create rmiregistry
within the server JVM with the port number passed as an argument.
 The rebind method of Naming class is used to bind the remote object to the new name.
 Java
// Java program for server application
import [Link].*;
import [Link].*;
public class SearchServer
{
public static void main(String args[])
{
try
{
// Create an object of the interface
// implementation class
Search obj = new SearchQuery();

// rmiregistry within the server JVM with


// port number 1900
[Link](1900);

// Binds the remote object by the name


// geeksforgeeks
[Link]("rmi://localhost:1900"+
"/geeksforgeeks",obj);
}
catch(Exception ae)
{
[Link](ae);
}
}
}

Step 6: Create and execute the client application program


The last step is to create the client application program and execute it on a separate command
prompt . The lookup method of the Naming class is used to get the reference of the Stub object.
 Java

// Java program for client application


import [Link].*;
public class ClientRequest
{
public static void main(String args[])
{
String answer,value="Reflection in Java";
try
{
// lookup method to find reference of remote object
Search access =
(Search)[Link]("rmi://localhost:1900"+
"/geeksforgeeks");
35

answer = [Link](value);
[Link]("Article on " + value +
" " + answer+" at GeeksforGeeks");
}
catch(Exception ae)
{
[Link](ae);
}
}
}

save the files respectively as per class name as


[Link] , [Link] , [Link] & [Link]

Important Observations:
1. RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to
create the distributed applications in java.
2. Stub and Skeleton objects are used for communication between the client
and server-side.

Distributed Architecture
In distributed architecture, components are presented on different platforms and
several components can cooperate with one another over a communication network in
order to achieve a specific objective or goal.

 In this architecture, information processing is not confined to a single machine


rather it is distributed over several independent computers.
 A distributed system can be demonstrated by the client-server architecture
which forms the base for multi-tier architectures; alternatives are the broker
architecture such as CORBA, and the Service-Oriented Architecture (SOA).
 There are several technology frameworks to support distributed architectures,
including .NET, J2EE, CORBA, .NET Web services, AXIS Java Web services,
and Globus Grid services.
 Middleware is an infrastructure that appropriately supports the development and
execution of distributed applications. It provides a buffer between the
applications and the network.
 It sits in the middle of system and manages or supports the different
components of a distributed system. Examples are transaction processing
monitors, data convertors and communication controllers etc.

Middleware as an infrastructure for distributed system


36

The basis of a distributed architecture is its transparency, reliability, and availability.

The following table lists the different forms of transparency in a distributed system −

Sr.N
Transparency & Description
o.

Access
1
Hides the way in which resources are accessed and the differences in data platform.

Location
2
Hides where resources are located.

Technology
3
Hides different technologies such as programming language and OS from user.

Migration / Relocation
4
Hide resources that may be moved to another location which are in use.

Replication
5
Hide resources that may be copied at several location.

Concurrency
6
Hide resources that may be shared with other users.

Failure
7
Hides failure and recovery of resources from user.

Persistence
8
Hides whether a resource ( software ) is in memory or disk.

Advantages
 Resource sharing − Sharing of hardware and software resources.
 Openness − Flexibility of using hardware and software of different vendors.
 Concurrency − Concurrent processing to enhance performance.
37

 Scalability − Increased throughput by adding new resources.


 Fault tolerance − The ability to continue in operation after a fault has
occurred.

Disadvantages
 Complexity − They are more complex than centralized systems.
 Security − More susceptible to external attack.
 Manageability − More effort required for system management.
 Unpredictability − Unpredictable responses depending on the system
organization and network load.

Centralized System vs. Distributed System

Criteria Centralized system Distributed System

Economics Low High

Availability Low High

Complexity Low High

Consistency Simple High

Scalability Poor Good

Technology Homogeneous Heterogeneous

Security High Low

Client-Server Architecture
The client-server architecture is the most common distributed system architecture
which decomposes the system into two major subsystems or logical processes −

 Client − This is the first process that issues a request to the second process
i.e. the server.
 Server − This is the second process that receives the request, carries it out,
and sends a reply to the client.

In this architecture, the application is modelled as a set of services that are provided
by servers and a set of clients that use these services. The servers need not know
about clients, but the clients must know the identity of servers, and the mapping of
processors to processes is not necessarily 1 : 1
38

Client-server Architecture can be classified into two models based on the functionality
of the client −

Thin-client model
In thin-client model, all the application processing and data management is carried by
the server. The client is simply responsible for running the presentation software.

 Used when legacy systems are migrated to client server architectures in which
legacy system acts as a server in its own right with a graphical interface
implemented on a client
 A major disadvantage is that it places a heavy processing load on both the
server and the network.

Thick/Fat-client model
In thick-client model, the server is only in charge for data management. The software
on the client implements the application logic and the interactions with the system
user.

 Most appropriate for new C/S systems where the capabilities of the client
system are known in advance
 More complex than a thin client model especially for management. New versions
of the application have to be installed on all clients.
39

Advantages
 Separation of responsibilities such as user interface presentation and business
logic processing.
 Reusability of server components and potential for concurrency
 Simplifies the design and the development of distributed applications
 It makes it easy to migrate or integrate existing applications into a distributed
environment.
 It also makes effective use of resources when a large number of clients are
accessing a high-performance server.

Disadvantages
 Lack of heterogeneous infrastructure to deal with the requirement changes.
 Security complications.
 Limited server availability and reliability.
 Limited testability and scalability.
 Fat clients with presentation and business logic together.

Multi-Tier Architecture (n-tier Architecture)


Multi-tier architecture is a client–server architecture in which the functions such as
presentation, application processing, and data management are physically separated.
By separating an application into tiers, developers obtain the option of changing or
adding a specific layer, instead of reworking the entire application. It provides a model
by which developers can create flexible and reusable applications.
40

The most general use of multi-tier architecture is the three-tier architecture. A three-
tier architecture is typically composed of a presentation tier, an application tier, and a
data storage tier and may execute on a separate processor.

Presentation Tier
Presentation layer is the topmost level of the application by which users can access
directly such as webpage or Operating System GUI (Graphical User interface). The
primary function of this layer is to translate the tasks and results to something that
user can understand. It communicates with other tiers so that it places the results to
the browser/client tier and all other tiers in the network.

Application Tier (Business Logic, Logic Tier, or Middle Tier)


Application tier coordinates the application, processes the commands, makes logical
decisions, evaluation, and performs calculations. It controls an application’s
functionality by performing detailed processing. It also moves and processes data
between the two surrounding layers.

Data Tier
In this layer, information is stored and retrieved from the database or file system. The
information is then passed back for processing and then back to the user. It includes
the data persistence mechanisms (database servers, file shares, etc.) and provides
API (Application Programming Interface) to the application tier which provides
methods of managing the stored data.
41

Advantages

 Better performance than a thin-client approach and is simpler to manage than a


thick-client approach.
 Enhances the reusability and scalability − as demands increase, extra servers
can be added.
 Provides multi-threading support and also reduces network traffic.
 Provides maintainability and flexibility

Disadvantages

 Unsatisfactory Testability due to lack of testing tools.


 More critical server reliability and availability.

Broker Architectural Style


Broker Architectural Style is a middleware architecture used in distributed computing
to coordinate and enable the communication between registered servers and clients.
Here, object communication takes place through a middleware system called an object
request broker (software bus).

 Client and the server do not interact with each other directly. Client and server
have a direct connection to its proxy which communicates with the mediator-
broker.
 A server provides services by registering and publishing their interfaces with the
broker and clients can request the services from the broker statically or
dynamically by look-up.
42

 CORBA (Common Object Request Broker Architecture) is a good


implementation example of the broker architecture.

Components of Broker Architectural Style


The components of broker architectural style are discussed through following heads −

Broker

Broker is responsible for coordinating communication, such as forwarding and


dispatching the results and exceptions. It can be either an invocation-oriented service,
a document or message - oriented broker to which clients send a message.

 It is responsible for brokering the service requests, locating a proper server,


transmitting requests, and sending responses back to clients.
 It retains the servers’ registration information including their functionality and
services as well as location information.
 It provides APIs for clients to request, servers to respond, registering or
unregistering server components, transferring messages, and locating servers.

Stub

Stubs are generated at the static compilation time and then deployed to the client side
which is used as a proxy for the client. Client-side proxy acts as a mediator between
the client and the broker and provides additional transparency between them and the
client; a remote object appears like a local one.

The proxy hides the IPC (inter-process communication) at protocol level and performs
marshaling of parameter values and un-marshaling of results from the server.

Skeleton

Skeleton is generated by the service interface compilation and then deployed to the
server side, which is used as a proxy for the server. Server-side proxy encapsulates
low-level system-specific networking functions and provides high-level APIs to mediate
between the server and the broker.

It receives the requests, unpacks the requests, unmarshals the method arguments,
calls the suitable service, and also marshals the result before sending it back to the
client.

Bridge
43

A bridge can connect two different networks based on different communication


protocols. It mediates different brokers including DCOM, .NET remote, and Java
CORBA brokers.

Bridges are optional component, which hides the implementation details when two
brokers interoperate and take requests and parameters in one format and translate
them to another format.

Broker implementation in CORBA

CORBA is an international standard for an Object Request Broker – a middleware to


manage communications among distributed objects defined by OMG (object
management group).

Service-Oriented Architecture (SOA)


A service is a component of business functionality that is well-defined, self-contained,
independent, published, and available to be used via a standard programming
interface. The connections between services are conducted by common and universal
message-oriented protocols such as the SOAP Web service protocol, which can
deliver requests and responses between services loosely.
44

Service-oriented architecture is a client/server design which support business-driven


IT approach in which an application consists of software services and software service
consumers (also known as clients or service requesters).

Features of SOA
A service-oriented architecture provides the following features −

 Distributed Deployment − Expose enterprise data and business logic as


loosely, coupled, discoverable, structured, standard-based, coarse-grained,
stateless units of functionality called services.
 Composability − Assemble new processes from existing services that are
exposed at a desired granularity through well defined, published, and standard
complaint interfaces.
 Interoperability − Share capabilities and reuse shared services across a
network irrespective of underlying protocols or implementation technology.
 Reusability − Choose a service provider and access to existing resources
exposed as services.

SOA Operation
The following figure illustrates how does SOA operate −

Advantages
45

 Loose coupling of service–orientation provides great flexibility for enterprises


to make use of all available service recourses irrespective of platform and
technology restrictions.
 Each service component is independent from other services due to the stateless
service feature.
 The implementation of a service will not affect the application of the service as
long as the exposed interface is not changed.
 A client or any service can access other services regardless of their platform,
technology, vendors, or language implementations.
 Reusability of assets and services since clients of a service only need to know
its public interfaces, service composition.
 SOA based business application development are much more efficient in terms
of time and cost.
 Enhances the scalability and provide standard connection between systems.
 Efficient and effective usage of ‘Business Services’.
 Integration becomes much easier and improved intrinsic interoperability.
 Abstract complexity for developers and energize business processes closer to
end users.

You might also like