Você está na página 1de 74

1

DISTRIBUTED SYSTEMS LAB


B.E. IV/IV I SEMESTER CSE-B
Academic year 2017-18

1. Write a program to demonstrate TCP Sockets in JAVA (Echo-Server).

2. Write a program to demonstrate UDP Sockets in JAVA (Echo-Server).

3. Write a program to demonstrate Chat Application using TCP.

4. Write a program to demonstrate Chat Application using UDP.

5. Write a program to demonstrate simple chat application with GUI.

6. Write a program to demonstrate RMI.

7. Write a program to implement DNS protocol using RMI.

8. Write a program to implement simple chat application using Threads.

9. Write a program to implement a 2PC (Two-Phase Commit Protocol) for distributed


transaction management.
10. Write a program to develop an FTP Client. Provide a GUI interface for the access of all the
services.(Like Uploading, Downloading, Listing the contents of directory, creating file/directory
etc.)
2
1. AIM: Write a program to demonstrate TCP Sockets in JAVA (Echo-Server).

Description:Sockets provide an interface for programming networks at the transport layer.


Network communicationusing Sockets is very much similar to performing file I/O. The streams
used in file I/O operation are also applicable to socket-based I/O. Socket-basedcommunication is
independent of a programming language used for implementing it. That means, a socketprogram
written in Java language can communicate to a program written in non-Java (say C or C++)
socketprogram.
A socket is an endpoint of a two-way communication link between two programs running on the
network.Socket is bound to a port number so that the TCP layer can identify the application that
data is destinedto be sent. Java provides a set of classes, defined in a package called java.net, to
enable the rapiddevelopment of network applications. The two key classes from the java.net
package used in creation of server and client programs are:
1.ServerSocket:This is used to create a server socket
2. Socket: This is used to create a socket
A server program creates a specific type of socket that is used to listen for client requests (server
socket),In the case of a connection request, the program creates a new socket through which it
will exchange datawith the client using input and output streams. The socket abstraction is very
similar to the file concept:developers have to open a socket, perform I/O, and close it.
TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain a
network conversation via which application programs can exchange data. TCP is a connection-
oriented protocol, which means a connection is established and maintained until the application
programs at each end have finished exchanging messages. It determines how to break application
data into packets that networks can deliver, sends packets to and accepts packets from the
network layer, manages flow control, andbecause it is meant to provide error-free data
transmissionhandles retransmission of dropped or garbled packets as well as
acknowledgement of all packets that arrive.
An "echo server" is a server that does nothing more than sending back whatever is sent to it.
The Echo server sends back to the same client the message it received. That is, when the server
receives a message from the client, the server echoes the message to the same client.

The steps for creating a simple server program are:


1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes(Hello\n);
5. Close socket:
client.close();
3
The steps for creating a simple client program are:
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(Hello\n);
4. Close the socket when done:
client.close();

Important classes/constructors/methods used in this program are:

public Socket(String host, int port)throws UnknownHostException, IOException:This


method attempts to connect to the specified server at the specified port. If this constructor does
not throw an exception, the connection is successful and the client is connected to the server.
InputStream: getInputStream() throws IOException: This method returns an Input Stream
representing the data and throws the appropriate exception if it cannot do so. Note that a
new InputStream object must be returned each time this method is called, and the stream must be
positioned at the beginning of the data.
OutputStream:getOutputStream() throws IOException:This method returns an
OutputStream where the data can be written and throws the appropriate exception if it cannot do
so. Note that a new OutputStream object must be returned each time this method is called, and
the stream must be positioned at the location the data is to be written.
DataInputStream(InputStream in): This creates a DataInputStream that uses the specified
underlying InputStream.
String readUTF():This method reads in a string that has been encoded using a modified UTF-8
format.
DataOutputStream(OutputStream out):This creates a new data output stream to write data to
the specified underlying output stream.
void writeUTF(String str):This method writes a string to the underlying output stream using
modified UTF-8 encoding in a machine-independent manner.
public ServerSocket(int port) throws IOException: Attempts to create a server socket bound
to the specified port. An exception occurs if the port is already bound by another application.
public Socket accept() throws IOException: Waits for an incoming client. This method blocks
until either a client connects to the server on the specified port or the socket times out, assuming
that the time-out value has been set using the setSoTimeout() method. Otherwise, this method
blocks indefinitely.
public void close() throws IOException: Closes the socket, which makes this Socket object no
longer capable of connecting again to any server.
4

SERVER PROGRAM

import java.net.*;
import java.io.*;
public classTCPServer
{
public static void main (String args[])
{
try
{
int serverPort = 7896;
ServerSocket listenSocket = new ServerSocket(serverPort);
while(true)
{
Socket clientSocket = listenSocket.accept();
Connection c = new Connection(clientSocket);
}
}
catch(IOException e)
{
System.out.println("Listen :"+e.getMessage());
}
}
}
class Connection extends Thread
{
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection (Socket aClientSocket)
{
try
{
clientSocket = aClientSocket;
in = new DataInputStream( clientSocket.getInputStream());
out =new DataOutputStream( clientSocket.getOutputStream());
this.start();
}
catch(IOException e)
{
System.out.println("Connection:"+e.getMessage());
}
}
public void run()
{
try
{ // an echo server
String data = in.readUTF();
out.writeUTF(data);
}
catch(EOFException e)
5
{
System.out.println("EOF:"+e.getMessage());
}
catch(IOException e)
{
System.out.println("IO:"+e.getMessage());
}
finally
{
try
{
clientSocket.close();
}
catch (IOException e)
{
/*close failed*/
}
}
}
}

CLIENT PROGRAM

import java.net.*;
import java.io.*;
public class TCPClient
{
public static void main (String args[])
{
// arguments supply message and hostname of destination
Socket s = null;
try
{
int serverPort = 7896;
s = new Socket(args[1], serverPort);
DataInputStream in = new DataInputStream( s.getInputStream());
DataOutputStream out =new DataOutputStream( s.getOutputStream());
out.writeUTF(args[0]); // UTF is a string encoding
String data = in.readUTF();
System.out.println("Received: "+ data) ;
}
catch (UnknownHostException e)
{
System.out.println("Sock:"+e.getMessage());
}
catch (EOFException e)
{
System.out.println("EOF:"+e.getMessage());
}
catch (IOException e)
{
System.out.println("IO:"+e.getMessage());
6
}
finally
{
if(s!=null)
try
{
s.close();
}
catch (IOException e)
{
System.out.println("close:"+e.getMessage());
}
}
}
}

OUTPUT
First compile both server and client programs
$:> javac TCPServer.java
$:> javac TCPClient.java
Then first run the server program
$:> java TCPServer
Then run the client program in another tab by passing two arguments (first: message,
Second: ServerAddress/localhost/127.0.0.1
$:> java TCPClient Connection oriented echo using TCP 127.0.0.1
Received: Connection oriented echo using TCP
7
2. AIM: Write a program to demonstrate UDP Sockets in JAVA (Echo-Server).

Description:UDP uses a simple connectionless communication model with a minimum of


protocol mechanism. It uses datagram packets. Datagram packets are used to implement a
connectionless packet delivery service supported by the UDP protocol. Each message is
transferred from source machine to destination based on information contained within that
packet. That means, each packet needs to have destination address and each packet might be
routed differently, and might arrive in any order. Packet delivery is not guaranteed.
An "echo server" is a server that does nothing more than sending back whatever is sent to it.
The Echo server sends back to the same client the message it received. That is, when the server
receives a message from the client, the server echoes the message to the same client.

The format of datagram packet is:


| Msg | length | Host | serverPort |
Java supports datagram communication through the following classes:
1. DatagramPacket
2. DatagramSocket
The class DatagramPacket contains several constructors that can be used for creating packet
object.
One of them is:
DatagramPacket(byte[] buf, int length, InetAddress address, int port);
This constructor is used for creating a datagram packet for sending packets of length length to
thespecified port number on the specified host. The message to be transmitted is indicated in the
first argument.
The key methods of DatagramPacket class are:
byte[] getData():Returns the data buffer.
int getLength():Returns the length of the data to be sent or the length of the data received.
void setData(byte[] buf):Sets the data buffer for this packet.
void setLength(int length):Sets the length for this packet.

The class DatagramSocket supports various methods that can be used for transmitting or
receivingdata using a datagram over the network. The two key methods are:
void send(DatagramPacket p): Sends a datagram packet from this socket.
void receive(DatagramPacket p):Receives a datagram packet from this socket.

Another java class used in this program is InetAddress class represents an IP address. The
java.net.InetAddress class provides methods to get the IP of any host name. Important method of
this class is
public static InetAddress getByName(String host) throws UnknownHostException:It
returns the instance of InetAddress containing LocalHost IP and name.
8
SERVER PROGRAM

import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main(String args[])
{
DatagramSocket aSocket = null;
try
{
aSocket = new DatagramSocket(6789);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),request.getLength(),request.getAddress(),
request.getPort());
aSocket.send(reply);
}
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
finally
{
if(aSocket != null)
aSocket.close();
}
}
}
9
CLIENT PROGRAM

import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main(String args[])
{
// args give message contents and server hostname
DatagramSocket aSocket = null;
try
{
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = 6789;
DatagramPacket request = new DatagramPacket(m, args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()));
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
finally
{
if(aSocket != null)
aSocket.close();
}
}
}
10
OUTPUT:
First compile both server and client programs
$:> javac UDPServer.java
$:> javac UDPClient.java
Then first run the server program
$:> java UDPServer
Then run the client program in another tab by passing two arguments (first: message,
Second: ServerAddress/localhost/127.0.0.1
$:> java UDPClient Connectionless Echo 127.0.0.1
Reply: Connectionless Echo
11
3. AIM: Write a program to demonstrate Chat Application using TCP.

Description:A socket is an endpoint of a two-way communication link between two programs


running on the network.Socket is bound to a port number so that the TCP layer can identify the
application that data is destinedto be sent. Java provides a set of classes, defined in a package
called java.net, to enable the rapiddevelopment of network applications. The two key classes
from the java.net package used in creation of server and client programs are:
1.ServerSocket:This is used to create a server socket
2. Socket: This is used to create a socket
A server program creates a specific type of socket that is used to listen for client requests (server
socket),In the case of a connection request, the program creates a new socket through which it
will exchange datawith the client using input and output streams. The socket abstraction is very
similar to the file concept:developers have to open a socket, perform I/O, and close it.
TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain a
network conversation via which application programs can exchange data. TCP is a connection-
oriented protocol, which means a connection is established and maintained until the application
programs at each end have finished exchanging messages. It determines how to break application
data into packets that networks can deliver, sends packets to and accepts packets from the
network layer, manages flow control, andbecause it is meant to provide error-free data
transmissionhandles retransmission of dropped or garbled packets as well as
acknowledgement of all packets that arrive.
Chat server is a stand-alone application that is made up with the combination of two-
application, server application (which runs on server side) and client application (which runs on
client side). This application is used for chatting in LAN. To start chatting you must be
connected with the server after that your message can broadcast to each and every client.
Important classes/constructors/methods used in this program are:

public Socket(String host, int port)throws UnknownHostException, IOException:This


method attempts to connect to the specified server at the specified port. If this constructor does
not throw an exception, the connection is successful and the client is connected to the server.
InputStream: getInputStream() throws IOException: This method returns an Input Stream
representing the data and throws the appropriate exception if it cannot do so. Note that a
new InputStream object must be returned each time this method is called, and the stream must be
positioned at the beginning of the data.
OutputStream:getOutputStream() throws IOException:This method returns an
OutputStream where the data can be written and throws the appropriate exception if it cannot do
so. Note that a new OutputStream object must be returned each time this method is called, and
the stream must be positioned at the location the data is to be written.
DataInputStream(InputStream in): This creates a DataInputStream that uses the specified
underlying InputStream.
String readUTF():This method reads in a string that has been encoded using a modified UTF-8
format.
DataOutputStream(OutputStream out):This creates a new data output stream to write data to
the specified underlying output stream.
void writeUTF(String str):This method writes a string to the underlying output stream using
modified UTF-8 encoding in a machine-independent manner.
public ServerSocket(int port) throws IOException: Attempts to create a server socket bound
to the specified port. An exception occurs if the port is already bound by another application.
12
public Socket accept() throws IOException: Waits for an incoming client. This method blocks
until either a client connects to the server on the specified port or the socket times out, assuming
that the time-out value has been set using the setSoTimeout() method. Otherwise, this method
blocks indefinitely.
public void close() throws IOException: Closes the socket, which makes this Socket object no
longer capable of connecting again to any server.
The java.lang.Thread class is a thread of execution in a program. The Java Virtual Machine
allows an application to have multiple threads of execution running concurrently.Following are
the important points about Thread
Every thread has a priority. Threads with higher priority are executed in preference to
threads with lower priority
Each thread may or may not also be marked as a daemon.
There are two ways to create a new thread of execution. One is to declare a class to be a
subclass of Thread (the one used in this program) and,
the other way to create a thread is to declare a class that implements the Runnable
interface
this.start() method causes this thread to begin execution, the Java Virtual Machine calls the run
method of this thread.The result is that two threads are running concurrently: the current thread
(which returns from the call to the start method) and the other thread (which executes its run
method).
void run():If this thread was constructed using a separate Runnable run object, then that
Runnable object's run method is called; otherwise, this method does nothing and returns.
BufferedReader class: BufferedReader class can be used to read data line by line by readLine()
method.Reads text from a character-input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
InputStreamReader class: InputStreamReader class can be used to read data from keyboard.It
performs two tasks:
o connects to input stream of keyboard
o converts the byte-oriented stream into character-oriented stream
System.in is an InputStream which is typically connected to keyboard input of console
programs.
java.io.BufferedReader.readline() : It is used to read a line of text. A line is considered to be
terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.
13
SERVER PROGRAM

import java.net.*;
import java.io.*;
public class TCPServerChat
{
public static void main (String args[])
{
try
{
int serverPort = 7896;
ServerSocket listenSocket = new ServerSocket(serverPort);
while(true)
{
Socket clientSocket = listenSocket.accept();
Connection c = new Connection(clientSocket);
}
}
catch(IOException e)
{
System.out.println("Listen :"+e.getMessage());
}
}
}
class Connection extends Thread
{
DataInputStream in;
DataOutputStream out;
Socket clientSocket;
public Connection (Socket aClientSocket)
{
try
{
clientSocket = aClientSocket;
in = new DataInputStream( clientSocket.getInputStream());
out =new DataOutputStream( clientSocket.getOutputStream());
this.start();
}
catch(IOException e)
{
System.out.println("Connection:"+e.getMessage());
}
}
public void run()
{
try
{
while(true)
{
String data = in.readUTF();
System.out.println("Received from Client: " + data);
System.out.println("Enter message to send");
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
14
String temp = dataIn.readLine();
out.writeUTF(temp);
}
}
catch(EOFException e)
{
System.out.println("EOF:"+e.getMessage());
}
catch(IOException e)
{
System.out.println("IO:"+e.getMessage());
}
finally
{
try
{
clientSocket.close();
}
catch (IOException e)
{
/*close failed*/
}
}
}
}
15
CLIENT PROGRAM

import java.net.*;
import java.io.*;
public class TCPClientChat
{
public static void main (String args[])
{
Socket s = null;
try
{
int serverPort = 7896;
s = new Socket(args[0], serverPort);
DataInputStream in = new DataInputStream( s.getInputStream());
DataOutputStream out = new DataOutputStream( s.getOutputStream());
while(true)
{
System.out.println("Enter message to send");
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
String temp = dataIn.readLine();
out.writeUTF(temp);
String data = in.readUTF();
System.out.println("Received from Server: "+ data) ;
}
}
catch (UnknownHostException e)
{
System.out.println("Sock:"+e.getMessage());
}
catch (EOFException e)
{
System.out.println("EOF:"+e.getMessage());
}
catch (IOException e)
{
System.out.println("IO:"+e.getMessage());
}
finally
{
if(s!=null)
try
{
s.close();
}
catch (IOException e)
{
System.out.println("close:"+e.getMessage());
}
}
}
}
16
OUTPUT:
First compile both server and client programs
$:> javac TCPServerChat.java
$:> javac TCPClientChat.java
Then first run the server program
$:> java TCPServerChat After that run the client program in
another tab by passing one argument i.e
(ServerAddress)
$:> java TCPClientchat 127.0.0.1
Enter message to send
TCP Chat Demo
Received from Client: TCP Chat Demo
Enter message to send
NiceDemo
Received from Server: Nice Demo
17
4.AIM:Write a program to demonstrate Chat Application using UDP.

Description:UDP uses a simple connectionless communication model with a minimum of


protocol mechanism. It uses datagram packets. Datagram packets are used to implement a
connectionless packet delivery service supported by the UDP protocol.
Chat server is a stand-alone application that is made up with the combination of two-
application, server application (which runs on server side) and client application (which runs on
client side). This application is used for chatting in LAN. To start chatting you must be
connected with the server after that your message can broadcast to each and every client
The format of datagram packet is:
| Msg | length | Host | serverPort |
Java supports datagram communication through the following classes:
1. DatagramPacket
2. DatagramSocket
The class DatagramPacket contains several constructors that can be used for creating packet
object.
One of them is:
DatagramPacket(byte[] buf, int length, InetAddress address, int port);
This constructor is used for creating a datagram packet for sending packets of length length to
thespecified port number on the specified host. The message to be transmitted is indicated in the
first argument.
The key methods of DatagramPacket class are:
byte[] getData():Returns the data buffer.
int getLength():Returns the length of the data to be sent or the length of the data received.
void setData(byte[] buf):Sets the data buffer for this packet.
void setLength(int length):Sets the length for this packet.

The class DatagramSocket supports various methods that can be used for transmitting or
receivingdata using a datagram over the network. The two key methods are:
void send(DatagramPacket p): Sends a datagram packet from this socket.
void receive(DatagramPacket p):Receives a datagram packet from this socket.

Another java class used in this program is InetAddress class represents an IP address. The
java.net.InetAddress class provides methods to get the IP of any host name. Important method of
this class is
public static InetAddress getByName(String host) throws UnknownHostException:It
returns the instance of InetAddress containing LocalHost IP and name.
BufferedReader class: BufferedReader class can be used to read data line by line by readLine()
method.Reads text from a character-input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
InputStreamReader class: InputStreamReader class can be used to read data from keyboard.It
performs two tasks:
o connects to input stream of keyboard
o converts the byte-oriented stream into character-oriented stream
java.io.BufferedReader.readline() : It is used to read a line of text. A line is considered to be
terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.
getBytes(): It returns the byte array of the string i.e; it returns sequence of bytes.
18
SERVER PROGRAM

import java.net.*;
import java.io.*;
public class UDPServerChat
{
public static void main(String args[])
{
DatagramSocket aSocket = null;
try
{
aSocket = new DatagramSocket(9999);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer, buffer.length);
aSocket.receive(request);
System.out.println("Received from Client: " + new String(request.getData()));
System.out.println("Enter message to send");
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
String temp = dataIn.readLine();
byte [] m = temp.getBytes();
DatagramPacket reply = new DatagramPacket(m,temp.length(), request.getAddress(), request.getPort());
aSocket.send(reply);
}
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
finally
{
if(aSocket != null)
aSocket.close();
}
}
}
19
CLIENT PROGRAM

import java.net.*;
import java.io.*;
public class UDPClientChat
{
public static void main(String args[])
{
// args give message contents and server
hostname DatagramSocket aSocket = null;
try
{
aSocket = new DatagramSocket();
InetAddress aHost = InetAddress.getByName(args[0]);
int serverPort = 9999;
while(true)
{
System.out.println("Enter message to send");
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
String temp = dataIn.readLine();
byte [] m = temp.getBytes();
DatagramPacket request = new DatagramPacket(m, temp.length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Received from Server: " + new String(reply.getData()));
}
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
finally
{
if(aSocket != null)
aSocket.close();
}
}
}
20
OUTPUT:
First compile both server and client programs
$:> javac UDPServerChat.java
$:> javac UDPClientChat.java
Then first run the server program
$:> java UDPServerChat After that run the client program in
another tab by passing one argument i.e
(ServerAddress)
$:> java UDPClientchat 127.0.0.1
Enter message to send
UDP Chat Demo

Received from Client: UDP Chat Demo


Enter message to send
NiceDemo
Received from Server: Nice Demo
21
5. AIM: Write a program to demonstrate simple chat application with GUI.

Description: TCP (Transmission Control Protocol) is a standard that defines how to establish and
maintain a network conversation via which application programs can exchange data. TCP is a
connection-oriented protocol, which means a connection is established and maintained until the
application programs at each end have finished exchanging messages. It determines how to break
application data into packets that networks can deliver, sends packets to and accepts packets
from the network layer, manages flow control, andbecause it is meant to provide error-free
data transmissionhandles retransmission of dropped or garbled packets as well as
acknowledgement of all packets that arrive.
Chat server is a stand-alone application that is made up with the combination of two-
application, server application (which runs on server side) and client application (which runs on
client side). This application is used for chatting in LAN. To start chatting you must be
connected with the server after that your message can broadcast to each and every client.
GUI stands for Graphical User Interface, a term used not only in Java but in all programming
languages that support the development of GUIs. A program's graphical user interface presents
an easy-to-use visual display to the user. It is made up of graphical components (e.g., buttons,
labels, windows) through which the user can interact with the page or application.
To make graphical user interfaces in Java, we use Swing.
A GUI includes a range of user interface elements.These can include:
Input controls such as buttons, dropdown lists, checkboxes and text fields.
Informational elements such as labels, banners, icons or notification dialogs.
Navigational elements, including sidebars and menus.
Swing is an API for creating GUI. It's designed with a modular architecture so that elements are
easily plug-and-play and can be customized.
javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
javax.swing.event package augments the java.awt.event package and defines event objects,
listeners, and adapters that are specific to Swing components. Classes with names ending in
"Event" define event types; their fields and methods provide details about the event that
occurred. Interfaces with names ending in "Listener" are event listeners. The methods of these
interfaces are invoked to notify interested objects when specific events occur.
javax.swing.borderpackage provides classes and interface for drawing specialized borders
around a Swing component.
java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
java.awt.eventpackage provides interfaces and classes for dealing with different types of events
fired by AWT components.
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
JFrame class is an extended version of java.awt.Frame that adds support for the JFC/Swing
component architecture.
The classes/methods/constructors used in this program are
JFrame():Constructs a new frame that is initially invisible.
JPanel:The JPanel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the JComponents class.
JButton:The JButton class is used to create a labeled button that has platform independent
22
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JButton(String s): It creates a button with the specified text.
JTextArea:The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class
JTextArea(int row, int column): Creates a text area with the specified number of rows and
columns that displays no text initially.
JScrollPane:A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size can change
dynamically.
JScrollPane(Component):It creates a scroll pane. The Component parameter, when present,
sets the scroll pane's client.
JTextField:The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
JTextField(int columns):Creates a new empty TextField with the specified number of columns.
JLabel:The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a user
cannot edit it directly. It inherits JComponent class.
JLabel(String s):Creates a JLabel instance with the specified text.
super(): super() can be used to invoke immediate parent class.
DataInputStream(InputStream in): This creates a DataInputStream that uses the specified
underlying InputStream.
PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.
LineBorder:This class draws a solid line of the specified color and thickness around a Swing
component. The default thickness is one pixel.
LineBorder (java.awt.Color color, int thickness, Boolean roundededges);
setBorder():To put a border around a JComponent.
BorderLayout arranges the components to fit in the five regions: east, west, north, south, and
center.
EmptyBorder (int top, int left, int bottom, int right); This class implements a transparent, empty
border. It is used to place a blank margin around a Swing component. The arguments to the
constructor specify the number of pixels of blank space to appear on each edge of the
component.
Action Listener:The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found in java.awt.event
package. The class which processes the ActionEvent should implement this interface. The object
can be registered using the addActionListener() method. When the action event occurs, that
object's actionPerformed method is invoked.
void actionPerformed(ActionEvent e):Invoked when an action occurs.
setEditable() method has one Boolean parameter. If the parameter is false, then the user cannot
type into the field.
voidsetDefaultCloseOperation(int Operation):Sets the operation that will happen by default
when the user initiates a "close" on this frame.
setSize(int width, int height): Used to set the size of JFrame.
setLocationRelativeTo(): This method allows you to set your Swing component's location
relative to another component.If the component is not visible or if you pass null, your JFrame
will be displayed on the screen center.
23
setVisible(boolean b):Shows or hides this component depending on the value of parameter b.
append(String str): This method appends the specified string to this character sequence.
getText(): This method is used to retrieve the text currently contained by the text field. The text
returned by this method does not include a newline character for the Enter key that fired the
action event.
flush() method flushes this output stream and forces any buffered output bytes to be written out.
void setText(String):Sets the text displayed by the text field.

SERVER PROGRAM

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class ServerChat extends JFrame implements ActionListener
{
JButton send = new JButton("SEND");
JTextArea area = new JTextArea(20,20);
JScrollPane jsp = new JScrollPane(area);
JTextField text = new JTextField(20);
JLabel label = new JLabel("Enter Ur Text :: ");
JPanel panel = new JPanel();
ServerSocket server;
Socket client;
DataInputStream din;
PrintWriter pw;
public ServerChat()
{
super("Server Window"); //super() can be used to invoke immediate parent class constructor.
panel.add(label); // add() is used to add components to the panel
panel.add(text);
panel.add(send);
panel.setBorder(new LineBorder(Color.red,2,true)); //red color with thickness 2 and rounded corners
add(panel,BorderLayout.SOUTH); // Align south
jsp.setBorder(new EmptyBorder(10,10,10,10));
add(jsp);
area.setFont(new Font("TimesRoman",Font.PLAIN,15)); // Font Style,Font Type and Font Size
area.setEditable(false);
send.addActionListener(this);
text.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500,500);
setLocationRelativeTo(null);
setVisible(true);
try
{
server = new ServerSocket(7000);
area.setText("Server Is Waiting For Client");
24
client = server.accept();
area.append("\nClient Is Now Connected");
pw = new PrintWriter(client.getOutputStream());
din = new DataInputStream(client.getInputStream());
}
catch(Exception e)
{
System.out.println("\n\tException " + e);
}
}
public void receive()
{
try
{
String s;
while((s=din.readLine())!=null)
{
String temp = "\nClient : " + s ;
area.append(temp);
}
}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
String s = "\nServer : " + text.getText() ;
area.append(s); pw.println(text.getText());
pw.flush();
text.setText("");
}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
public static void main(String args[])
{
new ServerChat().receive();
}
}
25

CLIENT PROGRAM

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class ClientChat extends JFrame implements ActionListener
{
JButton send = new JButton("SEND");
JTextArea area = new JTextArea(20,20);
JScrollPane jsp = new JScrollPane(area);
JTextField text = new JTextField(20);
JLabel label = new JLabel("Enter Ur Text :: ");
JPanel panel = new JPanel();
Socket client;
DataInputStream din;
PrintWriter pw;
public ClientChat()
{
super("Client Window");
panel.add(label);
panel.add(text);
panel.add(send);
panel.setBorder(new LineBorder(Color.red,2,true));
add(panel,BorderLayout.SOUTH);
jsp.setBorder(new EmptyBorder(10,10,10,10));
add(jsp);
send.addActionListener(this);
text.addActionListener(this);
area.setFont(new Font("TimesRoman",Font.PLAIN,15));
area.setEditable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500,500);
setLocationRelativeTo(null);
setVisible(true);
try
{
client = new Socket("localhost",7000);
pw = new PrintWriter(client.getOutputStream());
din = new DataInputStream(client.getInputStream());
}
catch(Exception e)
{
System.out.println("\n\tException " + e);
}
}
public void receive()
{
26
try
{
String s;
while((s=din.readLine())!=null)
{
String temp = "\nServer : " + s ;
area.append(temp);
}
}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
public void actionPerformed(ActionEvent ae)
{
try
{
String s = "\nClient : " + text.getText();
area.append(s);
pw.println(text.getText());
pw.flush();
text.setText("");
}
catch(Exception e)
{
System.out.println("Exception " + e);
}
}
public static void main(String args[])
{
new ClientChat().receive();
}
}
27
OUTPUT:
First compile both server and client programs
$:> javac ServerChat.java
$:> javac ClientChat.java
Then first run the Server program
$> java ServerChat
Now run the Client program in another tab
$> java ClientChat
28
6. AIM: Write a program to demonstrate RMI.

Description: RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object running
in another JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.A remote object is an object whose method can
be invoked from another JVM.
To write an RMI Java application, you would have to follow the steps given below
1. Define the remote interface
2. Develop the implementation class (remote object)
3. Develop the server program
4. Develop the client program
5. Compile the application which also involves using rmic.
6. Start the registry service by using rmiregistry.
7. Execute the application

1) Create the remote interface


For creating the remote interface, extend the Remote interface and declare the RemoteException
with all the methods of the remote interface. Here, we are creating a remote interface that
extends the Remote interface.
2)Provide the implementationof the remote interface
Now provide the implementation of the remote interface. For providing the implementation of
the Remote interface, we need to
o Either extend the UnicastRemoteObject class,
o or use the exportObject() method of the UnicastRemoteObject class
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the
RMI compiler and creates stub and skeleton objects.
4) Start the registry service by the rmiregistry tool
Now start the registry service by using the rmiregistry tool. If you don't specify the port number,
it uses a default port number. In this example, we are using the port number 5000.
5) Create and run the server application
Now rmi services need to be hosted in a server process. The Naming class provides methods to
get and store the remote object.
29
The Important Classes/Methods/Constructors used in this program are:
java.rmi.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:
o 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).
o 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.
java.rmi.RemoteException class is the superclass of exceptions thrown by the RMI runtime
during a remote method invocation. To ensure the robustness of applications using the RMI
system, each remote method declared in a remote interface must
specify java.rmi.RemoteException (or one of its superclasses such
as java.io.IOException or java.lang.Exception) in its throws clause.
java.rmi.server.UnicastRemoteObject class defines a singleton (unicast) remote object whose
references are valid only while the server process is alive.
NamingThe Naming class provides methods for storing and obtaining references to remote
objects in a remote object registry. Each method of the Naming class takes as one of its
arguments a name that is a java.lang.String in URL format of the form:
//host:port/name
where host is the host (remote or local) where the registry is located, port is the port number on
which the registry accepts calls, and where name is a simple string uninterpreted by the registry.
Both host and port are optional. If host is omitted, the host defaults to the local host. If port is
omitted, then the port defaults to 1099, the "well-known" port that RMI's registry, rmiregistry,
uses.
Binding a name for a remote object is associating or registering a name for a remote object that
can be used at a later time to look up that remote object. A remote object can be associated with
a name using the Naming class's bind or rebindmethods.
Once a remote object is registered (bound) with the RMI registry on the local host, callers on a
remote (or local) host can lookup the remote object by name, obtain its reference, and then
invoke remote methods on the object. A registry may be shared by all servers running on a host
or an individual server process may create and use its own registry if desired.
rebind(String name, Remote obj):Rebinds the specified name to a new remote object.
lookup(String name):Returns a reference, a stub, for the remote object associated with the
specified name.
Double.valueOf(String s):Returns a Double object holding the double value represented by the
argument string s.
doubleValue(): Returns the double value of this Double object.
30

AddServerIntf Program
import java.rmi.*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2) throws RemoteException;
}

AddServerImpl Program
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf
{
public AddServerImpl() throws RemoteException
{
}
public double add(double d1,double d2) throws RemoteException
{
return d1+d2;
}
}

AddServer Program (SERVER )


import java.rmi.*;
import java.rmi.server.*;
public class AddServer
{
public static void main(String args[])
{
try
{
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
}
catch(Exception e)
{
System.out.println("Exception:" +e);
}
}
}
31
AddClient Program (CLIENT)
import java.rmi.*;
public class AddClient
{
public static void main(String args[])
{
try
{
String addServerURL="rmi://"+args[0]+"/AddServer";
AddServerIntf addServerIntf= (AddServerIntf)Naming.lookup(addServerURL);
System.out.println("First no. is"+args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("Second no. is"+args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
System.out.println("the sum is "+addServerIntf.add(d1,d2));
}
catch(Exception e)
{
System.out.println("Exception:" +e);
}
}
}

OUTPUT:
First compile all the four programs (Remote interface, interface implementation class, server and
client) programs
$:> javac AddServerIntf.java
$:> javac AddServerImpl.java
$:> javac AddServer.java
$:> javac AddClient.java
Then Start the rmi registry using the following command.
$:>start rmiregistry (on windows) or rmiregistry& (on linux)
//This will start an rmi registry on a separate window
Now run the server class file.
$:> java AddServer
Now run the Client class filewith three arguments (Remote Server address,number1, number2) in
another tab
$> java AddClientlocalhost 10 30
First no. is10
Second no. is30
The sum is40.0
32
7. AIM: Write a program to implement DNS protocol using RMI.

Description:The Domain Name System (DNS) is a hierarchical decentralized naming system


for computers, services, or other resources connected to the Internet or a private network. It
associates various information with domain names assigned to each of the participating entities.
Most prominently, it translates more readily memorized domain names to the numerical IP
addresses needed for locating and identifying computer services and devices with the underlying
network protocols. By providing a worldwide, distributed directory service, the Domain Name
System is an essential component of the functionality on the Internet. Domain Name Service
maintains a table of (IP address, Domain Name) pairs.
RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
application in java. The RMI allows an object to invoke methods on an object running in another
JVM.
RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.A remote object is an object whose method can
be invoked from another JVM.
To write an RMI Java application to implement DNS protocol, we would have to follow the
steps given below
1. Define the remote interface
2. Develop the implementation class (map domain names to IP address)
3. Develop the server program
4. Develop the client program
5. Compile the application which also involves using rmic.
6. Start the registry service by using rmiregistry.
7. Execute the application
The Important Classes/Methods/Constructors used in this program are:
java.rmi.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.
java.rmi.RemoteException class is the superclass of exceptions thrown by the RMI runtime
during a remote method invocation. To ensure the robustness of applications using the RMI
system, each remote method declared in a remote interface
mustspecify java.rmi.RemoteException in its throws clause.
java.rmi.server.UnicastRemoteObject class defines a singleton (unicast) remote object whose
references are valid only while the server process is alive.
NamingThe Naming class provides methods for storing and obtaining references to remote
objects in a remote object registry. Each method of the Naming class takes as one of its
arguments a name that is a java.lang.String in URL format of the form:
//host:port/name
where host is the host (remote or local) where the registry is located, port is the port number on
which the registry accepts calls, and where name is a simple string uninterpreted by the registry.
Both host and port are optional. If host is omitted, the host defaults to the local host. If port is
omitted, then the port defaults to 1099, the "well-known" port that RMI's registry, rmiregistry,
uses.
Binding a name for a remote object is associating or registering a name for a remote object that
can be used at a later time to look up that remote object. A remote object can be associated with
33
a name using the Naming class's bind or rebind methods.
Once a remote object is registered (bound) with the RMI registry on the local host, callers on a
remote (or local) host can lookup the remote object by name, obtain its reference, and then
invoke remote methods on the object.
rebind(String name, Remote obj):Rebinds the specified name to a new remote object.
lookup(String name):Returns a reference, a stub, for the remote object associated with the
specified name.
String.equals(): This method compares the two given strings based on the content of the string.
If any character is not matched, it returns false. If all characters are matched, it returns true.

DNSServerIntf Program

import java.rmi.*;
public interface DNSServerIntf extends Remote
{
String DNS(String s1) throws RemoteException;
}

DNSServerImpl Program

import java.rmi.*;
import java.rmi.server.*;
public class DNSServerImpl extends UnicastRemoteObject implements DNSServerIntf
{
public DNSServerImpl() throws RemoteException
{
}
public String DNS(String s1) throws RemoteException
{
if(s1.equals("www.osmania.ac.in"))
return "50.32.24.29";
if(s1.equals("www.mjcollege.ac.in"))
return "90.82.44.89";
if(s1.equals("www.jntu.ac.in"))
return "150.32.64.20";
if(s1.equals("www.yahoo.com"))
return "88.39.124.129";
else
return "No Info about this address";
}
}

DNSServer Program (SERVER)

import java.rmi.*;
import java.rmi.server.*;
public class DNSServer
{
public static void main(String args[])
{
try
34
{
DNSServerImpl dnsServerImpl=new DNSServerImpl();
Naming.rebind("DNSServer",dnsServerImpl);
}
catch(Exception e)
{
System.out.println("Exception:" +e);
}
}
}

DNSClient Program (CLIENT)

import java.rmi.*;
public class DNSClient
{
public static void main(String args[])
{
try
{
String dnsServerURL="rmi://"+args[0]+"/DNSServer";
DNSServerIntf dnsServerIntf= (DNSServerIntf)Naming.lookup(dnsServerURL);
System.out.println("The website name is "+args[1]);
String s1=args[1];
System.out.println("The IP address is "+dnsServerIntf.DNS(s1));
}
catch(Exception e)
{
System.out.println("Exception:" +e);
}
}
}

OUTPUT:
First compile all the four programs (Remote interface, interface implementation class, server and
client) programs
$:> javac DNSServerIntf.java
$:> javac DNSServerImpl.java
$:> javac DNSServer.java
$:> javac DNSClient.java
Then Start the rmi registry using the following command.
$:>start rmiregistry (on windows) or rmiregistry& (on linux)
//This will start an rmi registry on a separate window
Now run the server class file.
$:> java DNSServer
Now run the Client class file with two arguments (Remote Server address, Domainname) in
another tab
$> java DNSClient localhost www.osmania.ac.in
The website name is www.osmania.ac.in
The IP address is 50.32.24.29
35
8. AIM: Write a program to implement simple chat application using Threads.

Description:In computer science, a thread of execution is the smallest sequence of programmed


instructions that can be managed independently by a scheduler, which is typically a part of
the operating system. Thread, in the context of Java, is the path followed when executing a
program. All Java programs have at least one thread, known as the main thread, which is created
by the JVM at the programs start, when the main() method is invoked with the main thread. In
Java, creating a thread is accomplished by implementing an interface and extending a class.
Every Java thread is created and controlled by the java.lang.Thread class.

When a thread is created, it is assigned a priority. The thread with higher priority is executed
first, followed by lower-priority threads. The JVM stops executing threads under either of the
following conditions:
If the exit method has been invoked and authorized by the security manager
All the daemon threads of the program have died
There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.

Important methods/constructors/classes used in this program are:


Runnable Interface:The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface have only one method
named run().
public void run():It is used to perform action for a thread.
start():starts the execution of the thread.JVM calls the run() method on the thread.It is a method
of thread class which is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds.
join(): waits for a thread to die.
String.equals(): This method compares the two given strings based on the content of the string.
If any character is not matched, it returns false. If all characters are matched, it returns true.
public Socket(String host, int port)throws UnknownHostException, IOException:This
method attempts to connect to the specified server at the specified port. If this constructor does
not throw an exception, the connection is successful and the client is connected to the server.
InputStream: getInputStream() throws IOException: This method returns an Input Stream
representing the data and throws the appropriate exception if it cannot do so.
OutputStream:getOutputStream() throws IOException: This method returns an
OutputStream where the data can be written and throws the appropriate exception if it cannot do
so.
DataInputStream(InputStream in): This creates a DataInputStream that uses the specified
underlying InputStream.
String readUTF():This method reads in a string that has been encoded using a modified UTF-8
format.
36
DataOutputStream(OutputStream out):This creates a new data output stream to write data to
the specified underlying output stream.
void writeUTF(String str):This method writes a string to the underlying output stream using
modified UTF-8 encoding in a machine-independent manner.
public ServerSocket(int port) throws IOException: Attempts to create a server socket bound
to the specified port. An exception occurs if the port is already bound by another application.
public Socket accept() throws IOException: Waits for an incoming client. This method blocks
until either a client connects to the server on the specified port or the socket times out, assuming
that the time-out value has been set using the setSoTimeout() method. Otherwise, this method
blocks indefinitely.
BufferedReader class: BufferedReader class can be used to read data line by line by readLine()
method.Reads text from a character-input stream, buffering characters so as to provide for the
efficient reading of characters, arrays, and lines.
InputStreamReader class: InputStreamReader class can be used to read data from keyboard.It
performs two tasks:
o connects to input stream of keyboard
o converts the byte-oriented stream into character-oriented stream
System.in is an InputStream which is typically connected to keyboard input of console
programs.
java.io.BufferedReader.readline() : It is used to read a line of text. A line is considered to be
terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.
public static InetAddress getLocalHost() throws UnknownHostException: It returns the
instance of InetAdddress containing local host name and address.
public void close() throws IOException: Closes the socket, which makes this Socket object no
longer capable of connecting again to any server.
37
SERVER PROGRAM

import java.net.*;
import java.io.*;
class NewThread1 implements Runnable
{
String name;
Thread t;
OutputStream os;
InputStream is;
DataOutputStream dos;
DataInputStream din;
BufferedReader dataIn;
NewThread1(String threadname,Socket s)
{
try
{
name=threadname;
t= new Thread(this,name);
System.out.println("New Thread1:"+t);
if(name.equals("Server Recieved"))
t.sleep(5000);
dos=new DataOutputStream(s.getOutputStream());
is=s.getInputStream();
dataIn=new BufferedReader(new InputStreamReader(System.in));
din=new DataInputStream(is);
t.start();
}
catch(Exception e)
{
System.out.println("Exception"+ name + e.getStackTrace());
}
}
public void run()
{
try
{
if(name.equals("Server Send"))
{
while(true)
{
String st= dataIn.readLine();
dos.writeUTF(st);
if(st.equals("end"))
{
t.sleep(1000);
break;
}
} //while
}//if
if(name.equals("Server Receive"))
{
38
while(true)
{
String sl= din.readUTF();
if(sl.equals("end"))
break;
System.out.println("SERVER RECIEVED:-- "+sl);
}//while
}//if
}//try
catch (Exception e)
{
System.out.println(name+" ");
}
System.out.println(name+" thread exiting.");
}//run
}//NewThread1
class TServer
{
public static void main(String args[]) throws Exception
{
try
{
ServerSocket ss=new ServerSocket(5005);
Socket s=ss.accept();
NewThread1 ob1= new NewThread1("Server Send",s);
NewThread1 ob2= new NewThread1("Server Received",s);
System.out.println("NOW START CHATTING");
ob1.t.join();
ob2.t.join();
}
catch(Exception e)
{
System.out.println("main thread interrupted");
}
System.out.println("main thread exiting");
}
}
39
CLIENT PROGRAM

import java.net.*;
import java.io.*;
class NewThread implements Runnable
{
String name; Thread t;
InputStream is;
OutputStream os;
DataOutputStream dos;
DataInputStream din;
BufferedReader dataIn;
NewThread(String threadname,Socket s1)
{
try
{
name=threadname;
t= new Thread(this,name);
System.out.println("New Thread:"+t);
dos=new DataOutputStream(s1.getOutputStream());
is=s1.getInputStream();
dataIn=new BufferedReader(new InputStreamReader(System.in));
din=new DataInputStream(is);
t.start();
}
catch(Exception e)
{
System.out.println("Exception: " + name +e);
System.out.println("Stack trace" + e.getStackTrace());
}
}
public void run()
{
try
{
if(name.equals("Client Send"))
{
while(true)
{
String st= dataIn.readLine();
dos.writeUTF(st);
if(st.equals("end"))
{
t.sleep(1000);
break;
}
}//while
}//if
if(name.equals("Client Received"))
{
while(true)
{
String sl= din.readUTF();
40
if(sl.equals("end"))
break;
System.out.println("Client Recieved:-- "+sl);
}//while
}//if
}//try
catch (Exception e)
{
System.out.println(name+" ");
}
System.out.println(name+" thread exiting.");
}//run
}//NewThread
class TClient
{
public static void main(String args[]) throws Exception
{
try
{
Socket s= new Socket(InetAddress.getLocalHost(),5005);
NewThread ob1= new NewThread("Client Send",s);
NewThread ob2= new NewThread("Client Received",s);
System.out.println("NOW START CHATTING");
ob1.t.join();
ob2.t.join();
}
catch(Exception e)
{
System.out.println("main thread interrupted" + e);
}
System.out.println("main thread exiting");
}
}
Output:
First compile both server and client programs Then run the client program in another tab
$:> javac TServer.java $:> java TCPClient
$:> javac TClient.java New Thread1: Thread[Server Send,5,main]
Then first run the server program New Thread1: Thread[Server
$:> java TServer Receive,5,main]
NOW START CHATTING

New Thread1: Thread[Server Send,5, main]


New Thread1: Thread[Server Receive,5, main]
NOW START CHATTING
Chat Demo
SERVER RECEIVED: Chat Demo
Good Demo Client Received: Good Demo
end
Server Receive thread exiting Client Send thread exiting
Server still sending Client Received: Server still sending
end
Server Send thread exiting Client Receive thread exiting
main thread exiting main thread exiting
41
9. AIM: Write a program to implement a 2PC (Two-Phase Commit Protocol) for
distributed transaction management.
Description: In transaction processing, databases, and computer networking, the two-phase
commit protocol (2PC) is a type of atomic commitment protocol (ACP). It is a distributed
algorithm that coordinates all the processes that participate in a distributed atomic transaction on
whether to commit or abort (roll back) the transaction (it is a specialized type of consensus
protocol). The protocol achieves its goal even in many cases of temporary system failure
(involving either process, network node, communication, etc. failures), and is thus widely used.
However, it is not resilient to all possible failure configurations, and in rare cases, user (e.g., a
system's administrator) intervention is needed to remedy an outcome.
In a "normal execution" of any single distributed transaction ( i.e., when no failure occurs, which
is typically the most frequent situation), the protocol consists of two phases:
1. The commit-request phase (or voting phase), in which a coordinator process attempts to
prepare all the transaction's participating processes (named participants, cohorts,
or workers) to take the necessary steps for either committing or aborting the transaction
and to vote, either "Yes": commit (if the transaction participant's local portion execution
has ended properly), or "No": abort (if a problem has been detected with the local
portion), and
2. The commit phase, in which, based on voting of the cohorts, the coordinator decides
whether to commit (only if all have voted "Yes") or abort the transaction (otherwise), and
notifies the result to all the cohorts. The cohorts then follow with the needed actions
(commit or abort) with their local transactional resources (also called recoverable
resources; e.g., database data) and their respective portions in the transaction's other
output (if applicable).
Message flow of 2PC protocol.

Coordinator Participants
QUERY TO COMMIT
-------------------------------->
VOTE YES/NO prepare*/abort*
<-------------------------------
commit*/abort* COMMIT/ROLLBACK
-------------------------------->
ACKNOWLEDGMENT commit*/abort*
<--------------------------------
end

The important Classes/Constructors/Methods used in this program are:

Runnable Interface:The Runnable interface should be implemented by any class whose


instances are intended to be executed by a thread. Runnable interface have only one method
named run().
public void run():It is used to perform action for a thread.
start():starts the execution of the thread.JVM calls the run() method on the thread.It is a method
of thread class which is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
42
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
join(): waits for a thread to die.
String.equals(): This method compares the two given strings based on the content of the string.
If any character is not matched, it returns false. If all characters are matched, it returns true.
public Socket(String host, int port)throws UnknownHostException, IOException:This
method attempts to connect to the specified server at the specified port. If this constructor does
not throw an exception, the connection is successful and the client is connected to the server.
InputStream: getInputStream() throws IOException: This method returns an Input Stream
representing the data and throws the appropriate exception if it cannot do so.
OutputStream:getOutputStream() throws IOException: This method returns an
OutputStream where the data can be written and throws the appropriate exception if it cannot do
so.
DataInputStream(InputStream in): This creates a DataInputStream that uses the specified
underlying InputStream.
DataOutputStream(OutputStream out):This creates a new data output stream to write data to
the specified underlying output stream.
public ServerSocket(int port) throws IOException: Attempts to create a server socket bound
to the specified port. An exception occurs if the port is already bound by another application.
public Socket accept() throws IOException: Waits for an incoming client. This method blocks
until either a client connects to the server on the specified port or the socket times out, assuming
that the time-out value has been set using the setSoTimeout() method. Otherwise, this method
blocks indefinitely.
readline() : It is used to read a line of text. A line is considered to be terminated by any one of a
line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
public static InetAddress getLocalHost() throws UnknownHostException: It returns the
instance of InetAdddress containing local host name and address.
public void close() throws IOException: Closes the socket, which makes this Socket object no
longer capable of connecting again to any server.
PrintStream class provides methods to write data to another stream. The PrintStream class
automatically flushes the data so there is no need to call flush() method. Moreover, its methods
don't throw IOException.
this is a reference variable that refers to the current object.
getStackTrace() method returns an array of stack trace elements, each representing one stack
frame. The zeroth element of the array represents the top of the stack, which is the last method
invocation in the sequence. This is the point at which this throwable was created and thrown.
Integer.parseInt() method: It is used to convert String to int.
synchronized method: It is used to lock an object for any shared resource. When a thread
invokes a synchronized method, it automatically acquires the lock for that object and releases it
when the thread completes its task. Every object has a lock associated with it. By convention, a
thread that needs consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.
Math.random(): It returns a double value with a positive sign, greater than or equal to 0.0 and
less than 1.0.
43
COORDINATOR

import java.net.*;
import java.io.*;
class NewThread implements Runnable
{
String name;
Thread t;
Socket s;
OutputStream os;
InputStream is;
PrintStream ps;
DataInputStream in;
Counter c;
NewThread(String threadname,Counter c,int portnumber)
{
try
{
this.c=c;
name=threadname;
t= new Thread(this,name);
s = new Socket(InetAddress.getLocalHost(),portnumber);
os = s.getOutputStream();
is = s.getInputStream();
ps = new PrintStream(os);
in = new DataInputStream(is);
t.start();
}//try
catch(Exception e)
{
System.out.println("Exception: "+name+e.getStackTrace());
}
}//Constructor
public void run()
{
try
{
ps.println("Can Commit?");
System.out.println("Asking the participant whether to commit?");
String s1 = in.readLine();
if(s1.equals("Yes Commit"))
{
c.increment();
System.out.println(c.counter);
while(c.counter<c.nump);
if(c.allflag)
{
System.out.println("Recieved 'Yes Commit' from participant.");
ps.println("Commit");
System.out.println("Asking participant to Commit.");
s1=in.readLine();
if(s1.equals("ack"))
44
{
System.out.println("coordinator rcvs Acknolodgement");
System.out.println("Coordinator committed.");
}
}
else
{
ps.println("Rollback");
System.out.println("Asking participant to Rollback.");
s1=in.readLine();
if(s1.equals("ack"))
{
System.out.println("coordinator rcvs Acknolodgement");
System.out.println("Coordinator rolled back.");
}
}
}
else if(s1.equals("Failure"))
{
c.allflag=false;
System.out.println("Recieved 'Failure' from participant.");
ps.println("Rollback");
c.increment();
System.out.println("Asking participant to Rollback.");
s1=in.readLine();
if(s1.equals("ack"))
{
System.out.println("coordinator rcvs Acknolodgement");
System.out.println("Coordinator rolled back.");
}
}
}//try
catch(Exception e)
{
System.out.println("Exception"+ name + e.getStackTrace());
}
}//run
}//NewThread
class Coordinator
{
public static void main(String args[]) throws Exception
{
int portnumber = 7000;
Counter c = new Counter();
int numP = Integer.parseInt(args[0]);
c.nump=numP;
NewThread ob[]= new NewThread[5];
for(int i=0;i<numP;i++)
{
ob[i] = new NewThread("Participant",c,portnumber);
portnumber++;
}
for(int i=0;i<numP;i++)
45
{
ob[i].t.join();
}
}//main
}//class Coordinator
class Counter
{
public static int counter;
public static boolean allflag=true;
public static int nump;
synchronized int increment()
{
counter++;
return 0;
}
}

PARTICIPANT

import java.net.*;
import java.io.*;
class Participant
{
public static void main(String args[]) throws Exception
{
int portnumber = Integer.parseInt(args[0]);
ServerSocket ss = new ServerSocket(portnumber);
Socket s = ss.accept();
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
PrintStream ps = new PrintStream (os);
DataInputStream din = new DataInputStream(is);
Thread t=new Thread();
String s1 = din.readLine();
if(s1.equals("Can Commit?"))
{
System.out.println("Recieved 'Can Commit?' from coordinator.");
}
double i = Math.random()*10;
int flag = (int) i;
System.out.println("Random number generated is " + flag);
if(flag == 1 || flag == 2 || flag == 3)
{
ps.println("Failure");
System.out.println("Sent 'Failure' to coordinator.");
}
else
{
ps.println("Yes Commit");
System.out.println("Sent 'Yes Commit' to coordinator.");
}
String s2 = din.readLine();
46
if(s2.equals("Commit"))
{
System.out.println("Recieved 'Commit' from coordinator.");
ps.println("ack");
System.out.println("Participant committed.");
}
else if(s2.equals("Rollback"))
{
System.out.println("Recieved 'Rollback' from coordinator.");
ps.println("ack");
System.out.println("Participant Rolled back.");
}
s.close();
}
}

OUTPUT:
First compile both Coordinator and Participant programs
$:> javac Coordinator.java
$:> javac Participant.java
Now first run (2-3) participants each in separate tab by passing portnumber in increasing
order as an argument.
$:> java Participant 7000
In another tab
$:> java Participant 7001
In another tab
$:> java Participant 7002
Then run Coordinator program in another tab by passing number of participants (2-3) as
an argument.
$:> java Coordinator 3
Asking the participant whether to commit?
1
Asking the participant whether to commit?
2
Asking the participant whether to commit?
3
Recieved 'Yes Commit' from participant.
Recieved 'Yes Commit' from participant.
Recieved 'Yes Commit' from participant.
Asking participant to Commit.
Asking participant to Commit.
Asking participant to Commit.
coordinator rcvs Acknolodgement.
coordinator rcvs Acknolodgement.
coordinator rcvs Acknolodgement.
Coordinator committed.
Coordinator committed.
Coordinator committed.
On Participants screen the output is
java Participant 7000 ( on its screen)
Recieved 'Can Commit?' from coordinator.
47
Random number generated is 7
Sent 'Yes Commit' to coordinator.
Recieved 'Commit' from coordinator.
Participant committed.
On Participants screen the output is
java Participant 7001 ( on its screen)
Recieved 'Can Commit?' from coordinator.
Random number generated is 7
Sent 'Yes Commit' to coordinator.
Recieved 'Commit' from coordinator.
Participant committed.

On Participants screen the output is


java Participant 7002 ( on its screen)
Recieved 'Can Commit?' from coordinator.
Random number generated is 4
Sent 'Yes Commit' to coordinator.
Recieved 'Commit' from coordinator.
Participant committed.

Second time the output is


$:> java Coordinator 3
Asking the participant whether to commit?
1
Asking the participant whether to commit?
2
Asking the participant whether to commit?
3
Recieved 'Failure' from participant.
Asking participant to Rollback.
Asking participant to Rollback.
Asking participant to Rollback.
coordinator rcvs Acknolodgement.
coordinator rcvs Acknolodgement.
coordinator rcvs Acknolodgement.
Coordinator rolled back.
Coordinator rolled back.
Coordinator rolled back.
On Participants screen the output is
java Participant 7000 ( on its screen)
Recieved 'Can Commit?' from coordinator.
Random number generated is 5
Sent 'Yes Commit' to coordinator.
Recieved 'Rollback' from coordinator.
Participant Rolled back.
On Participants screen the output is
java Participant 7001 ( on its screen)
Recieved 'Can Commit?' from coordinator.
Random number generated is 2
Sent Failure to coordinator.
48
Recieved 'Rollback' from coordinator.
Participant Rolled back.

On Participants screen the output is


java Participant 7002 ( on its screen)
Recieved 'Can Commit?' from coordinator.
Random number generated is 7
Sent 'Yes Commit' to coordinator.
Recieved 'Rollback' from coordinator.
Participant Rolled back.
Screenshot of output
Coordinator

Participant1

Participant2

Participant3
49
Second case of output
Coordinator

Participant1

Participant2

Participant3
50
10. AIM:Write a program to develop an FTP Client. Provide a GUI interface for the access
of all the services.(Like Uploading, Downloading, Listing the contents of directory, creating
file/directory etc.)
Description: File Transfer Protocol (FTP) is the commonly used protocol for
exchanging files over the Internet. FTP uses the Internet's TCP/IPprotocols to enable data
transfer. FTP uses a client-server architecture, often secured with SSL/TLS. FTP promotes
sharing of files via remote computers with reliable and efficient data transfer.
FTP Client Application can be developed to Upload, Download & list files/directories to/from a
server from/to a local system.
GUI stands for Graphical User Interface, a term used not only in Java but in all programming
languages that support the development of GUIs. A program's graphical user interface presents
an easy-to-use visual display to the user. It is made up of graphical components (e.g., buttons,
labels, windows) through which the user can interact with the page or application.
To make graphical user interfaces in Java, we use Swing.
A GUI includes a range of user interface elements.These can include:
Input controls such as buttons, dropdown lists, checkboxes and text fields.
Informational elements such as labels, banners, icons or notification dialogs.
Navigational elements, including sidebars and menus.
Swing is an API for creating GUI. It's designed with a modular architecture so that elements are
easily plug-and-play and can be customized.
javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
javax.swing.event package augments the java.awt.event package and defines event objects,
listeners, and adapters that are specific to Swing components. Classes with names ending in
"Event" define event types; their fields and methods provide details about the event that
occurred. Interfaces with names ending in "Listener" are event listeners. The methods of these
interfaces are invoked to notify interested objects when specific events occur.
javax.swing.borderpackage provides classes and interface for drawing specialized borders
around a Swing component.
java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
java.awt.eventpackage provides interfaces and classes for dealing with different types of events
fired by AWT components.
There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to
break string.
sun.net.TelnetInputStream: This class provides input and output streams for telnet clients.
sun.net.ftp.FtpClient: A class that implements the FTP protocol according to RFCs 959, 2228,
2389, 2428, 3659, 4217, which includes support for FTP over SSL/TLS. FtpClient provides all
the functionalities of a typical FTP client, like storing or retrieving files, listing or creating
directories. A typical usage would consist of connecting the client to the server, log in, issue a
few commands then logout.
JFrame class is an extended version of java.awt.Frame that adds support for the JFC/Swing
component architecture.
The classes/methods/constructors used in this program are
JFrame():Constructs a new frame that is initially invisible.
JPanel:The JPanel is a simplest container class. It provides space in which an application can
51
attach any other component. It inherits the JComponents class.
JButton:The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
JButton(String s): It creates a button with the specified text.
JTextArea:The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class
JTextArea(int row, int column): Creates a text area with the specified number of rows and
columns that displays no text initially.
JScrollPane:A JscrollPane is used to make scrollable view of a component. When screen size is
limited, we use a scroll pane to display a large component or a component whose size can change
dynamically.
JScrollPane(Component):It creates a scroll pane. The Component parameter, when present,
sets the scroll pane's client.
JTextField:The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
JTextField(int columns):Creates a new empty TextField with the specified number of columns.
JPasswordField: The object of a JPasswordField class is a text component specialized for
password entry. It allows the editing of a single line of text. It inherits JTextField class.
JPasswordField(int columns):Constructs a new empty JPasswordField with the specified
number of columns.
super(): super() can be used to invoke immediate parent class.
JLabel:The object of JLabel class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by an application but a user
cannot edit it directly. It inherits JComponent class.
JLabel(String s):Creates a JLabel instance with the specified text.
DataInputStream(InputStream in): This creates a DataInputStream that uses the specified
underlying InputStream.
PrintWriter class is the implementation of Writer class. It is used to print the formatted
representation of objects to the text-output stream.
LineBorder:This class draws a solid line of the specified color and thickness around a Swing
component. The default thickness is one pixel.
LineBorder (java.awt.Color color, int thickness, Boolean roundededges);
setBorder():To put a border around a JComponent.
BorderLayout arranges the components to fit in the five regions: east, west, north, south, and
center.
EmptyBorder (int top, int left, int bottom, int right); This class implements a transparent, empty
border. It is used to place a blank margin around a Swing component. The arguments to the
constructor specify the number of pixels of blank space to appear on each edge of the
component.
FlowLayout: FlowLayout is used to arrange the components in a line, one after another (in a
flow). It is the default layout of applet or panel.
setLayout method: Containers layout manager can be set using this method.
getContentPane(): This method retrieves the content pane layer so that you can add an object to
it. The content pane is an object created by the Java run time environment. You do not have to
know the name of the content pane to use it.
WindowAdapter: An abstract adapter class for receiving window events. The methods in this
class are empty. This class exists as convenience for creating listener objects.
52
WindowListener: The listener interface for receiving window events. The class that is interested
in processing a window event either implements this interface (and all the methods it contains) or
extends the abstract WindowAdapter class (overriding only the methods of interest). The listener
object created from that class is then registered with a Window using the window's
addWindowListener method. When the window's status changes by virtue of being opened,
closed, activated or deactivated, iconified or deiconified, the relevant method in the listener
object is invoked, and the WindowEvent is passed to it.
windowClosing(WindowEvent e):Invoked when the user attempts to close the window from
the window's system menu.
getPredefinedCursor(int type): Returns a cursor object with the specified predefined type.
public static final int WAIT_CURSOR: The wait cursor type.
public static final int DEFAULT_CURSOR:The default cursor type (gets set if no cursor is
defined).
setCursor(Cursor cursor):Sets the cursor image to the specified cursor. This cursor image is
displayed when the contains method for this component returns true for the current cursor
location, and this Component is visible, displayable, and enabled. Setting the cursor of a
Container causes that cursor to be displayed within all of the container's subcomponents, except
for those that have a non-null cursor.
public char[] getPassword():Returns the text contained in this TextComponent. If the
underlying document is null, will give a NullPointerException. For stronger security, it is
recommended that the returned character array be cleared after use by setting each character to
zero.
java string indexOf(): This method returns index of given character value or substring. If it is
not found, it returns -1. The index counter starts from zero.
substring(): It is used for getting a substring of a particular String.
String substring(int beginIndex): Returns the substring starting from the specified
index(beginIndex) till the end of the string.
String substring(int beginIndex, int endIndex): Returns the substring starting from the given
index(beginIndex) till the specified index(endIndex).
java string lastIndexOf() method returns last index of the given character value or substring. If
it is not found, it returns -1. The index counter starts from zero.
public boolean login(String username,String password) throws IOException: Login to the
FTP server using the provided username and password.
setMessage(int status): Sets the parameters for a MIDI (Musical Instrument Digital Interface)
message that takes no data bytes.
Runnable Interface:The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. Runnable interface have only one method
named run().
public void run():It is used to perform action for a thread.
start():starts the execution of the thread.JVM calls the run() method on the thread.It is a method
of thread class which is used to start a newly created thread. It performs following tasks:
A new thread starts(with new callstack).
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
SwingUtilities.invokeLater(): Simply schedules the GUI creation task and returns.
Action Listener:The Java ActionListener is notified whenever you click on the button or menu
item. It is notified against ActionEvent. The ActionListener interface is found in java.awt.event
package. The class which processes the ActionEvent should implement this interface. The object
53
can be registered using the addActionListener() method. When the action event occurs, that
object's actionPerformed method is invoked.
void actionPerformed(ActionEvent e):Invoked when an action occurs.
setEditable() method has one Boolean parameter. If the parameter is false, then the user cannot
type into the field.
setSize(int width, int height): Used to set the size of JFrame.
setVisible(boolean b):Shows or hides this component depending on the value of parameter b.
append(String str): This method appends the specified string to this character sequence.
repaint():Adds the specified region to the dirty region list if the component is showing. The
component will be repainted after all of the currently pending events have been dispatched.
getText(): This method is used to retrieve the text currently contained by the text field. The text
returned by this method does not include a newline character for the Enter key that fired the
action event.
flush() method flushes this output stream and forces any buffered output bytes to be written out.
void setText(String):Sets the text displayed by the text field.
protected: It is a access modifier which is accessible within package and outside the package but
through inheritance only. The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
FileOutputStream: It is an output stream used for writing data to a file.
java string toLowerCase(): This method returns the string in lowercase letter. In other words, it
converts all characters of the string into lower case letter.
hasMoreTokens(): This method is used to test if there are more tokens available from this
tokenizer's string.

FTPClient (CLIENT PROGRAM)

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.border.*;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
public class FTPClient extends JFrame
{
public static int BUFFER_SIZE = 10240;
protected JTextField userNameTextField = new JTextField("anonymous");
protected JPasswordField passwordTextField = new JPasswordField(10);
protected JTextField urlTextField = new JTextField(20);
protected JTextField fileTextField = new JTextField(10);
protected JTextArea monitorTextArea = new JTextArea(5, 20);
protected JButton ftpc = new JButton("ftpc");
protected FtpClient ftpClient;
protected String localFileName;
protected String remoteFileName;

public FTPClient()
{
super("FTP Client -- GET/PUT LIST");
54
JPanel p = new JPanel();
p.setBorder(new EmptyBorder(5, 5, 5, 5));
p.setLayout(new FlowLayout());
p.add(new JLabel("User name:")); // add() is used to add components to the panel
p.add(userNameTextField);
p.add(new JLabel("Password:"));
p.add(passwordTextField);
p.add(new JLabel("URL:"));
p.add(urlTextField);
p.add(new JLabel("File:"));
p.add(fileTextField);
p.add(ftpc);
monitorTextArea.setEditable(false);
JScrollPane ps = new JScrollPane(monitorTextArea);
p.add(ps);
getContentPane().add(p, BorderLayout.CENTER);
WindowListener wndCloser = new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
disconnect();
System.exit(0);
}
};
addWindowListener(wndCloser);
setSize(720, 240);
setVisible(true);
}
public void setButtonStates(boolean state)
{
ftpc.setEnabled(state);
}
protected boolean connect()
{
monitorTextArea.setText("");
setButtonStates(false);
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
String user = userNameTextField.getText();
if (user.length() == 0)
{
setMessage("Please enter user name");
setButtonStates(true);
return false;
}
String password = new String(passwordTextField.getPassword());
String sUrl = urlTextField.getText();
if (sUrl.length() == 0)
{
setMessage("Please enter URL");
setButtonStates(true);
return false;
}
localFileName = fileTextField.getText();
55
// Parse URL
int index = sUrl.indexOf("//");
if (index >= 0)
sUrl = sUrl.substring(index + 2);
index = sUrl.indexOf("/");
String host = sUrl.substring(0, index);
sUrl = sUrl.substring(index + 1);
String sDir = "";
index = sUrl.lastIndexOf("/");
if (index >= 0)
{
sDir = sUrl.substring(0, index);
sUrl = sUrl.substring(index + 1);
}
remoteFileName = sUrl;
try
{
setMessage("Connecting to host " + host);
ftpClient = new FtpClient(host);
ftpClient.login(user, password);
setMessage("User " + user + " login OK");
setMessage(ftpClient.welcomeMsg);
ftpClient.cd(sDir);
setMessage("Directory: " + sDir);
ftpClient.binary();
return true;
}
catch (Exception ex)
{
setMessage("Error: " + ex.toString());
setButtonStates(true);
return false;
}
}
protected void disconnect()
{
if (ftpClient != null)
{
try
{
ftpClient.closeServer();
}
catch (IOException ex)
{
}
ftpClient = null;
}
Runnable runner = new Runnable()
{
public void run()
{
ftpc.setEnabled(true);
FTPClient.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
56
}
};
SwingUtilities.invokeLater(runner);
}
protected void setMessage(final String str)
{
if (str != null)
{
Runnable runner = new Runnable()
{
public void run()
{
monitorTextArea.append(str + '\n');
monitorTextArea.repaint();
}
};
SwingUtilities.invokeLater(runner);
}
}
}

FTPGetClient Program

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.border.*;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
public class FTPGetClient extends FTPClient
{
public FTPGetClient()
{
super();
ActionListener lst = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (connect())
{
Thread downloader = new Thread()
{
public void run()
{
getFile();
disconnect();
}
};
downloader.start();
}
57
}
};
ftpc.addActionListener(lst);
}
protected void getFile()
{
if (localFileName.length() == 0)
{
localFileName = remoteFileName;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
fileTextField.setText(localFileName);
}
}
);
}
byte[] buffer = new byte[BUFFER_SIZE];
try
{
FileOutputStream out = new FileOutputStream(localFileName);
InputStream in = ftpClient.get(remoteFileName);
int counter = 0;
while (true)
{
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
}
out.close();
in.close();
}
catch (Exception ex)
{
setMessage("Error: " + ex.toString());
}
}
public static void main(String argv[])
{
new FTPGetClient();
}
}

FTPPutClient Program

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.StringTokenizer;
58
import javax.swing.*;
import javax.swing.border.*;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
public class FTPPutClient extends FTPClient
{
public FTPPutClient()
{
super();
ActionListener lst = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (connect())
{
Thread uploader = new Thread()
{
public void run()
{
putFile();
disconnect();
}
};
uploader.start();
}
}
};
ftpc.addActionListener(lst);
}
protected void putFile()
{
if (localFileName.length() == 0)
{
setMessage("Please enter file name");
}
byte[] buffer = new byte[BUFFER_SIZE];
try
{
File f = new File(localFileName);
int size = (int) f.length();
setMessage("File " + localFileName + ": " + size + " bytes");
FileInputStream in = new FileInputStream(localFileName);
OutputStream out = ftpClient.put(remoteFileName);
int counter = 0;
while (true)
{
int bytes = in.read(buffer);
if (bytes < 0)
break;
out.write(buffer, 0, bytes);
counter += bytes;
}
out.close();
59
in.close();
}
catch (Exception ex)
{
setMessage("Error: " + ex.toString());
}
}
public static void main(String argv[])
{
new FTPPutClient();
}
}

FTPListClient Program

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.swing.border.*;
import sun.net.TelnetInputStream;
import sun.net.ftp.FtpClient;
public class FTPListClient extends FTPClient
{
public FTPListClient()
{
super();
ActionListener ftpcl = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if (connect())
{
Thread downloader = new Thread()
{
public void run()
{
getList();
disconnect();
}
};
downloader.start();
}
}
};
ftpc.addActionListener(ftpcl);
}
protected void getList()
{
try
{
60
TelnetInputStream lst = ftpClient.list();
String str = "";
while (true)
{
int c = lst.read();
char ch = (char) c;
if (c < 0 || ch == '\n')
{
str = str.toLowerCase();
{
StringTokenizer tk = new StringTokenizer(str);
int index = 0;
while (tk.hasMoreTokens())
{
String token = tk.nextToken();
if (index = =8) //index of file names check the index on ftpserver on which it is executed.
try
{
setMessage(token); //System.out.println(token);
}
catch (NumberFormatException ex)
{
}
index++;
}
}
str = "";
}
if (c <= 0)
break;
str += ch;
}
}
catch (Exception ex)
{
setMessage("Error: " + ex.toString());
}
}
public static void main(String argv[])
{
new FTPListClient();
}
}

OUTPUT:

First compile all the four programs (i.e; FTPClient, FTPGetClient, FTPPutClient,
FTPListClient
$:> javac FTPClient.java
$:> javac FTPGetClient.java
$:> javac FTPPutClient.java
$:> javac FTPListClient.java
61

Then run the three programs


$:> java FTPGetClient
$:> java FTPPutClient
$:> java FTPListClient

GET

PUT
62

LIST
63
11. STUDY OF NFS.
Network File System (NFS) is a network file system protocol originally developed by Sun
Microsystems in 1984, allowing a user on a client computer to access files over a network in a
manner similar to how local storage is accessed.
NFS, like many other protocols, builds on the Open Network Computing Remote Procedure Call
(ONC RPC) system. The Network File System is an open standard defined in RFCs, allowing
anyone to implement the protocol.
NFS allows a system to share directories and files with others over a network. By using NFS,
users and programs can access files on remote systems almost as if they were local files.
Some of the most notable benefits that NFS can provide are:
Local workstations use less disk space because commonly used data can be stored on a
single machine and still remain accessible to others over the network.
There is no need for users to have separate home directories on every network machine.
Home directories could be set up on the NFS server and made available throughout the
network.
Storage devices such as floppy disks, CDROM drives, and Zip drives can be used by
other machines on the network. This may reduce the number of removable media drives
throughout the network.
Network File System is a client/server application designed by Sun Microsystems that allows all
network users to access shared files stored on computers of different types. NFS provides access
to shared files through an interface called the Virtual File System (VFS) that runs on top of
TCP/IP. Users can manipulate shared files as if they were stored locally on the user's own hard
disk. With NFS, computers connected to a network operate as clients while accessing remote
files, and as servers while providing remote users access to local shared files.
NFS is a stateless protocol. The benefit of the stateless protocol is that there is no need to do state
recovery after a client or server crash

NFS Architecture:
64
NFS support Unix system calls. The integration of the distributed file systems that support UNIX
system calls is achieved by a Virtual File System(VFS) module.
VFS is added to UNIX kernel to distinguish between local and remote files and to translate
between the UNIX-independent file identifiers used by NFS and the internal file identifiers
normally used in UNIX and other file systems.VFS keeps track of the file systems that are
currently available both locally and remotely, and it passes each request to the appropriate local
system module.
How NFS Works:
NFS consists of at least two main parts: a server and one or more clients. The client remotely
accesses the data that is stored on the server machine. In order for this to function properly a few
processes have to be configured and running.
The server has to run the following daemons:
Daemon Description
nfsd: The NFS daemon which services requests from the NFS clients.
mountd: The NFS mount daemon which carries out the requests that nfsd passes on to it.
rpcbind: This daemon allows NFS clients to discover which port the NFS server is using.

The client can also run a daemon, known as nfsiod. The nfsiod daemon services the requests
from the NFS server. This is optional, and improves performance, but is not required for normal
and correct operation.
NAME
nfsd -- remote NFS server
SYNOPSIS
nfsd [-ardute] [-nnum_servers] [-hbindip]
DESCRIPTION
The nfsd utility runs on a server machine to service NFS requests from client machines. At least
one nfsd must be running for a machine to operate as a server.
NAME
nfsiod -- local NFS asynchronous I/O server
SYNOPSIS
nfsiod [-nnum_servers]
DESCRIPTION
The nfsiod utility is a kernel process which runs on an NFS client machine to service
asynchronous I/O requests to its server. It improves performance but is not required for correct
operation.
Configuring NFS:
NFS configuration is a relatively straightforward process. The processes that need to be running
can all start at boot time with a few modifications to your /etc/rc.conffile.
On the NFS server, make sure that the following options are configured in the /etc/rc.conf file:
rpcbind_enable="YES"
nfs_server_enable="YES"
mountd_flags="-r"
mountd runs automatically whenever the NFS server is enabled.
On the client, make sure this option is present in /etc/rc.conf:
nfs_client_enable="YES"
The /etc/exports file specifies which file systems NFS should export (sometimes referred to as
share). Each line in /etc/exports specifies a file system to be exported and which machines
65
have access to that file system. Along with what machines have access to that file system, access
options may also be specified.
There are many such options that can be used in this file but only a few are mentioned here.
Locking:
Some applications (e.g. mutt) require file locking to operate correctly. In the case of NFS,
rpc.lockd can be used for file locking. To enable it, add the following to the /etc/rc.conf file on
both client and server (it is assumed that the NFS client and server are configured already):
rpc_lockd_enable="YES"
rpc_statd_enable="YES"
Start the application by using:
# /etc/rc.d/lockd start
# /etc/rc.d/statd start
If real locking between the NFS clients and NFS server is not required, it is possible to let the
NFS client do locking locally by passing -L to mount_nfs(8).
Versions and variations:
Original NFS version:
The implementation details are defined in RFC 1094. Sun used version 1 only for in-house
experimental purposes. When the development team added substantial changes to NFS version 1
and released it outside of Sun, they decided to release the new version as v2, so that version
interoperation and RPC version fallback could be tested.
NFSv2:
Version 2 of the protocol (defined in RFC 1094, March 1989) originally operated entirely over
UDP. Its designers meant to keep the protocol stateless, with locking (for example) implemented
outside of the core protocol. People involved in the creation of NFS version 2 include Rusty
Sandberg, Bob Lyon, Bill Joy, and Steve Kleiman.
NFSv2 only allowed the first 2 GB of a file to be read.
NFSv3:
Version 3 (RFC 1813, June 1995) added:
Support for 64-bit file sizes and offsets, to handle files larger than 2 gigabytes (GB);
Support for asynchronous writes on the server, to improve write performance;
Additional file attributes in many replies, to avoid the need to re-fetch them;
READDIRPLUS operation, to get file handles and attributes along with file names when
scanning a directory;
Assorted other improvements.
At the time of introduction of Version 3, vendor support for TCP as a transport layer protocol
began increasing. While several vendors had already added support for NFS Version 2 with TCP
as a transport, Sun Microsystems added support for TCP as a transport for NFS at the same time
it added support for Version 3. Using TCP as a transport made using NFS over a WAN more
feasible.
NFSv4:
Version 4 (RFC 3010, December 2000; revised in RFC 3530, April 2003), influenced by AFS
and CIFS, includes performance improvements, mandates strong security, and introduces a
stateful protocol.[3] Version 4 became the first version developed with the Internet Engineering
Task Force (IETF) after Sun Microsystems handed over the development of the NFS protocols.
NFS version 4 minor version 1 (NFSv4.1) has been approved by the IESG and received
an RFC number since Jan 2010. The NFSv4.1 specification aims:
To provide protocol support to take advantage of clustered server deployments including the
ability to provide scalable parallel access to files distributed among multiple servers
66
Other extensions:
WebNFS, an extension to Version 2 and Version 3, allows NFS to integrate more easily into
Web-browsers and to enable operation through firewalls. In 2007, Sun Microsystems open
sourced their client-side WebNFS implementation.
Various side-band protocols have become associated with NFS, including:
The byte-range advisory Network Lock Manager (NLM) protocol (added to support
UNIX System V file-locking APIs).
The remote quota reporting (RQUOTAD) protocol (to allow NFS-users to view their
data-storage quotas on NFS servers).
NFS over RDMA is an adaptation of NFS that uses RDMA as a transport.
Platforms:
NFS is often used with Unix operating systems such as Solaris, AIX, HP-UX, FreeBSD and
Unix-like operating systems (such as Linux). It is also available to operating systems such as the
classic Mac OS, OpenVMS, Microsoft Windows, Novell NetWare, and IBM AS/400.
Alternative remote file access protocols include the Server Message Block (SMB, also known as
CIFS), Apple Filing Protocol (AFP), NetWare Core Protocol (NCP), and OS/400 File Server file
system (QFileSvr.400). SMB and NetWare Core Protocol (NCP) occur more commonly than
NFS on systems running Microsoft Windows; AFP occurs more commonly than NFS in
Macintosh systems; and QFileSvr.400 occurs more commonly in AS/400 systems.
Typical implementation:
Assuming a Unix-style scenario in which one machine (the client) requires access to data stored
on another machine (the NFS server):
1. The server implements NFS daemon processes (running by default as nfsd) in order to make
its data generically available to clients.
2. The server administrator determines what to make available, exporting the names and
parameters of directories (typically using the /etc/exports configuration file and the exportfs
command).
3. The server security-administration ensures that it can recognize and approve validated clients.
4. The server network configuration ensures that appropriate clients can negotiate with it through
any firewall system.
5. The client machine requests access to exported data, typically by issuing a mount command.
(The client asks the server (rpcbind) which port the NFS server is using, the client connects to
the NFS server (nfsd), nfsd passes the request to mountd)
6. If all goes well, users on the client machine can then view and interact with mounted
filesystems on the server within the parameters permitted.
Note that automation of the NFS mounting process may take place perhaps using /etc/fstab
and/or automounting facilities.
Protocol development versus competing protocols:
1980s
NFS and ONC figured prominently in the network-computing war between Sun Microsystems
and Apollo Computer, and later the UNIX wars (ca 1987-1996)between AT&T and Sun on one
side, and Digital Equipment, HP, and IBM on the other.
During the development of the ONC protocol (called SunRPC at the time), only Apollo's
Network Computing System (NCS) offered comparable functionality.
Two competing groups developed over fundamental differences in the two remote procedure call
systems. Arguments focused on the method for data-encoding ONC's External Data
Representation (XDR) always rendered integers in big-endian order, even if both peers of the
connection had little-endian machine architectures, whereas NCS's method attempted to avoid
67
byte-swap whenever two peers shared a common endianness in their machine-architectures. An
industry group called the Network Computing Forum formed (March 1987) in an (ultimately
unsuccessful) attempt to reconcile the two network-computing environments.
Later, Sun and AT&T announced that the two firms would jointly develop AT&T's next version
of UNIX: System V Release 4. This caused many of AT&T's other licensees of UNIX System V
to become concerned that this would put Sun in an advantaged position, and it ultimately led to
Digital Equipment, HP, IBM, and others forming the Open Software Foundation (OSF) in 1988.
Ironically, Sun and AT&T had previously competed over Sun's NFS versus AT&T's Remote File
System (RFS), and the quick adoption of NFS over RFS by Digital Equipment, HP, IBM, and
many other computer vendors tipped the majority of users in favor of NFS.
OSF solicited the proposals for various technologies, including the remote procedure call (RPC)
system and the remote file access protocol. In the end, proposals for these two requirements,
called respectively, the Distributed Computing Environment (DCE), and the Distributed File
System (DFS) won over Sun's proposed ONC and NFS. DCE derived from a suite of
technologies, including NCS and Kerberos. DFS used DCE as the RPC and derived from AFS.
1990s
Sun Microsystems and the Internet Society (ISOC) reached an agreement to cede "change
control" of ONC RPC so that ISOC's engineering-standards body, the Internet Engineering Task
Force (IETF), could publish standards documents (RFCs) documenting the ONC RPC protocols
and could extend ONC RPC. OSF attempted to make DCE RPC an IETF standard, but ultimately
proved unwilling to give up change-control. Later, the IETF chose to extend ONC RPC by
adding a new authentication flavor based on GSSAPI, RPCSEC GSS, in order to meet IETF's
requirements that protocol standards have adequate security.
Later, Sun and ISOC reached a similar agreement to give ISOC change control over NFS,
although writing the contract carefully to exclude NFS version 2 and version 3. Instead, ISOC
gained the right to add new versions to the NFS protocol, which resulted in IETF specifying NFS
version 4 in 2003.
Present
NFSv4.1 adds the Parallel NFS pNFS capability, which enables data access parallelism. The
NFSv4.1 protocol defines a method of separating the filesystem meta-data from the location of
the file data; it goes beyond the simple name/data separation by striping the data amongst a set of
data servers. This is different from the traditional NFS server which holds the names of files and
their data under the single umbrella of the server. There exist products which are multi-node NFS
servers, but the participation of the client in separation of meta-data and data is limited. The
NFSv4.1 client can be enabled to be a direct participant in the exact location of file data and
avoid solitary interaction with the single NFS server when moving data.
The NFSv4.1 pNFS server is a collection of server resources or components; these are
assumed to be controlled by the meta-data server.
The pNFS client still accesses a single meta-data server for traversal or interaction with
the namespace; when the client moves data to and from the server it may be directly interacting
with the set of data servers belonging to the pNFS server collection.
In addition to pNFS, NFSv4.1 provides Sessions, Directory Delegation and Notifications,
Multi-server Namespace, ACL/SACL/DACL, Retention Attributions, and
SECINFO_NO_NAME.
Practical Uses:
NFS has many practical uses. Some of the more common ones are listed below:
Set several machines to share a CDROM or other media among them. This is cheaper and
often a more convenient method to install software on multiple machines.
68
On large networks, it might be more convenient to configure a central NFS server in
which to store all the user home directories. These home directories can then be exported
to the network so that users would always have the same home directory, regardless of
which workstation they log in to.
Several machines could have a common /usr/ports/distfiles directory. That way, when
you need to install a port on several machines, you can quickly access the source without
downloading it on each machine.
NFS SERVER OPERATION:
Operation Meaning
lookup(dirfh ,name) Returns file handle and attributes for the file
name in the directory dirfh
Create(dirfh, name, attr) Creates a new file name in the directory dirfh
with attributes attr and returns the new file
handle and attributes
remove (dirfh, name) Removes file name from the directory dirfh
getattr ( fh) Returns file attributes of the file
Setattr(fh,attr) Set the attributes (mode, userid, groupid, size,
accesstime, and modify time of a file).Setting
the size to zero truncates the file.
read (fh, offset, count) Returns upto count bytes of data from a file
starting at offset also returns the latest
attributes of the file.
Write(fh, offset,count,data) Writes count bytes of data to a file starting at
offset. Returns the attribute of the file after the
write has taken place.
Rename(dirfh, name, todirfh, toname) Changes the name of file name in the directory
dirfh to to_name in directory dirfh
Link(newdirfh,newname , fh ) Creates an entry new name in the directory
newdirfh which refers to the file or directory
fh)
Symlink(newdirfh,newname,striing) Creates an entry new name in the directory
new dirfh of type symbolic link but with the
value string.
Readlink(fh) Returns the string that is associated with the
symbolic link file identified by fh
Mkdir(dirfh, name , attr) Creates a new directory name with attributes
attr and returns the new file handle and
attributes
Rmdir(dirfh,name) Removes the empty directory name from the
parent directory dirfh fails if the directory is
not empty
Readdir(dirfh,cookie,count) Returns upto count bytes of directory entries
from the directory dirfh. Each entry contains a
file name, a file handle and an opaque pointer
to the next directory entry called a cookie
Statfs(fh) Returns the filesystem information for the
filesystem containing a file fh
69
12. CASE STUDY: DATA BASE REPLICATION
Defining Replication
Replication in distributed systems is the maintenance of copies of data at multiple computers as a
technique for automatically maintaining the availability of data despite server failures according
to Coulouris, Dollimore, and Kindberg. Along with this definition there is the requirement that
replicas of data reside on failure-independent machines. Data consistency is of primary concern
in replication schemes due to the nature of multiple accesses occurring at once. Replication
transparency is also highly desired; user should be unaware of how and where the data being
accessed is stored.
History
Replication has taken various forms through its evolution. Initially, replication was simply data
copied to tape and stored in anticipation of corruption or failure. When needed, the back-up data
source replaced the original. Many problems existed in such a system. For one, if all the back-up
data sources were stored close together in the same facility and an environmental factor distorted
or destroyed one of the back-ups, more than likely the others were also affected. Also, when a
data source needed to be replaced the machine that housed it had to be shutdown. This meant
nodes trying to access any data from the machine needing the replacement data source had to
wait for the data source swap out and the machine to come back online. Much production time
was wasted in this type of system.
With distributed systems, individual machines on the system hold copies of data from
other machines. Each member of the system holds partial or complete duplicates of other
machines data. This means if the original source for the data goes down for maintenance or its
data becomes corrupt, the data it houses is still accessible from other sources on the system.
While the original data source may experience downtime, the system users are unaware of it.
This is a great improvement over the previous method.
More recently the Internet has created a new spin on distributed systems, peer-to-peer
resource trading. In these systems, each peer can communicate with other peers to replicate its
own collections of data. Nodes on these systems share their storage space with each other as a
means of self-preservation. Through this propagation technique, data sources virtually guarantee
continuous and seamless data access.
Goals
There are three primary goals for data replication: increased availability, increased fault-
tolerance, and data consistency. Replication transparency is a lesser goal. The motivations for
replication are to improve a services performance, to increase its availability, or to make it fault-
tolerant. The use of replication enhances distributed systems by restricting or eliminating
downtime by having multiple copies of data in various stores. When a clients primary source of
requested data is down or has a long wait, the client can attempt to access the data from another
server. This only works, however, as long as the data copies are stored at failure-independent
locations.
Data consistency is another goal of data replication. It is often difficult to maintain. There
are two main options on how to approach data consistency. The first is to block access to all
other copies of a file while one of them is being updated. This is a tedious and resource intensive
solution. The most often used option is merge copies of a file after updates have taken place.
This becomes a complex task, however, with the more copies there are of a file.
There is a balance to strict in balancing the conflicting goals of replication, data
availability and consistency. If consistency is not of primary importance, it can be sacrificed for
availability and performance. This is an incarnation of a fundamental trade-off in the area of
fault-tolerance.
70
Features
Transparency is the most important feature of replication. Replication transparency is the
appearance that only the original data store exists. Users should be unaware of the presence of
multiple copies and unable to distinguish between the original and its replicas. This is achieved
through the use of various addressing schemes. The servers maintain address cross references
between data and their replicas. When updates take place, the servers work to reconcile their
copies with the updated data.
Consistency among data stores and their replicas is another very important feature of
replication. Since multiple users are able to access replicas of the same file from different
servers, it is necessary to account for simultaneous updates to the same data. This can be done
using system blocks during the updates or data merges afterward. Either way there is increased
difficulty with the more replicas that exist.
There are two models of replication regarding fault-tolerance, passive and active. One is
used over the other based on the desired effect on the system and the tolerable level of
complexity.
Passive, or primary back-up, replication systems have a single primary RM and one or
two secondary (back-up) replica managers also called slaves. The textbook definition of this
model requires the front ends to communicate solely with the primary replica manager for
services. Data updates are handled by the primary replica manager and propagated through to the
slave replication managers. This model can be used in most systems, even with primary
replication managers that behave in a non-deterministic manner due to complex processes such
as multithreading.
Active replication managers function as groups versus the passive models hierarchical
structure. Requests for services are multicast to the group from the front ends. All replica
managers reply to every request independently, so if one server crashes, the client should see no
evidence of it. Data consistency is also preserved through this model since the front ends receive
multiple responses for the same request. These responses can be compared to determine accuracy
of data.

Structure
For data replication to occur certain players must be present. There must be servers each with its
own set of clients. These clients are not exclusive to a particular server, but do rely primarily on
one for services. If that server is bottlenecked or unavailable the clients may request assistance
from other servers. The servers are also not exclusive to their clients. They will serve any client
requesting services they can provide. These servers are also referred to as replica managers
71
(RM). RMs are responsible for maintaining and operating directly on the replicas they hold and
these operations must be recoverable. Frequently replication systems require RMs to be state
machines. The data files that the RMs hold are called objects.
Client requests for services (operations) do not actually go directly to an RM. Instead
they go through a type of dispatcher known as a front end (FE). FEs helps filter requests and
determine which requests should go to which RMs. There are five phases needed to complete a
single transaction request, coordination, execution, agreement, and response.
A basic architectural model for the management of replicated data

Replication systems can be far more complicated than the example presented here.
Multicast communications and group membership services are two facilities that can be added to
a replication system to increase its functionality.
How to Use
From the clients perspective no there appear to be no difference between working on a
replicated versus a non-replicated system. The client need not even be aware of which system he
is using.
The server side of a replicated system is very different, however. In order to use
replication effectively, some predictive calculations must be made. One of these is the cost of
replication transactions. The availability of stored data should also be determined since this is
one of the primary goals of replication. This can be done using the following equation:
n servers, probability p of server access failure
1-probability(all servers fail) = 1 - pn
The other main objective of replicated systems is to provide a higher level of faulttolerance. The
better the fault-tolerance, the higher the availability of replicated data. In a system where there is
a minimal acceptable level of data availability this can be critical. Availability can be
predictively determined using the following :
If f of f+1 servers crash, then 1 server is still operating and if up to f servers can exhibit
Byzantine failures, then 2f+1 servers would permit full function during most worst case scenarios
Once all this planning has been done, the hardware installation starts. Servers acting as RMs
need to be installed. The communication between the RMs should be tested. Then FEs should be
setup up for the clients. After that, the system is ready to operate using the five transaction steps
described in the above section on structure.
72
What is Database Replication?
Database replication is a highly flexible technology for copying updates automatically
between databases. The idea is that if you make a change to one database, the other database
copies the update automatically. Replication occurs at the database level and does not require
any special actions from client applications.
Propagating updates automatically is a simple idea, but it helps solve a surprisingly large
number of problems. See below for a summary figure of solution examples. The examples are
also explained into more detail - clockwise - in the list below the figure.
Replication Benefits

1. Availability. Keeping multiple copies of data is one of the most effective ways to avoid
database availability problems. If one database fails, you can switch to another local copy or
even to a copy located on another site.
2. Cross-site database operation. Applications like credit card processing use multiple open
databases on different sites, so that there is always a database available for transactions.
Replication can help transfer copies between distributed databases or send updates to a centrally
located copy.
3. Scaling. Replicated copies are live database, so you can use them to distribute read traffic. For
example, you can run backups or reports on a replica without affecting other copies.
4. Upgrades. Replication allows users to upgrade a replica, which can then be switched over to
the master copy. This is a classic technique to minimize downtime as well as provide a
convenient back-out in the event of problems.
5. Heterogeneous database integration. It is quite common for data to be entered in one database
type, such as PostgreSQL, and used in another, such as MySQL. Replication can copy data
between databases and perform transformations necessary to ensure proper conversion.
6. Data warehouse loading. Replication applies updates in real-time, which is very useful as
databases become too large to move using batch processes. Data warehouse loading is much
easier with capabilities such as transforming data or copying updates to a central location.
7. Geographic distribution. Replication allows users to place two or more clusters in
geographically separated locations to protect against site failure or site unreachability.
It is not surprising that database replication is considered essential technology to build
and operate a wide variety of business-critical applications. Tungsten Replicator is designed to
solve the problems described above as well as many others.
How Does Replication Work?
Tungsten Replicator uses master/slave replication. In master/slave replication, updates are
handled by one database server, known as the master, and propagated automatically to replicas,
which are known as slaves. This is a very efficient way to make database copies and keep them
up to date as they change.
Master/slave replication is based on a simple idea. Let us assume that two databases start
with the same initial data, which we call a snapshot. We make changes on one database,
recording them in order so that they can be replayed with exactly the same effect as the original
changes. We call this a serialized order. If we replay the serialized order on the second database,
we have master/slave replication.
73
Master/Slave Replication

Master/slave replication is popular for a number of reasons. First, databases can generate
and reload snapshots relatively efficiently using backup tools. Second, databases not only
serialize data very quickly but also write it into a file-based log that can be read by external
processes. Master/slave replication is therefore reasonably tractable to implement, even though
the effort to do it well is not small.
Master/slave replication has a number of benefits for users. It runs very quickly, places
few limitations on user SQL, and works well over high latency network connections typical of
wide area networks (WAN). Also, as Tungsten Replicator demonstrates, this type of replication
does not require any changes to the database server itself, which means that it works with off-
the-shelf databases.
Master/slave replication also has some disadvantages. First, the master is a single point of
failure. Special procedures are necessary to handle this and keep systems available. Second,
slaves tend to lag the master. This is due to the fact that masters can typically process updates
faster than they can be replicated and applied to slaves.
Tungsten Replicator is designed to minimize drawbacks of the approach, for example by
handling master failover correctly or providing mechanisms to help boost speed of updates on
replicas. It also has features like data filtering and transformation, which make it better able to
handle problems like heterogeneous data integration for which master/slave replication is
uniquely suited.
Applications
Many applications utilize replication to improve performance. Two very different applications
are explained below. The first is the use of replication to optimize domain name system
performance. The second explores replication schemes such as the one used by for Napster.
In order to ease bottlenecks at root servers, replicas of these servers are propagated throughout
the world. This not only prevents the root server from becoming overwhelmed by the number of
requests it receives, but also decreases the service time per request by having more servers
available and closer to the requesters. When new sites join the Internet, their local DNS servers
are configured to a list of root servers. Frequently, the physically closet server has the best
response.
A community-based redundancy system consists of a group of peers that cooperate with
each other to provide resource redundancy . Through this group effort reliability and fault
tolerance are increased for all the peers involved. Each peer is able to take advantage of a
system with large aggregate resources simply by contributing its own, relatively small set of
resources. Second, the distribution of resources in the system means that the value of the
aggregate resources is larger than the sum of the individual contributions . This does bring up
the question of resource allocation for each of the peers. They must determine what resources
can be spared for the community and what resources must be held back for its necessary
functions and performance.
Benefits and Issues
74
Aside from the obvious benefit of reduced or eliminated downtime during a server crash, there is
also the benefit of shortened service time to consider. With multiple copies of data scattered
throughout a system, it is probable that replicas of desired data are closer than the original data
store thereby reducing service time. While the difference in access time may only a matter of
thousandths or millionths of a second, when working with hundreds of files, this shortened time
delay can have a perceivable impact.
As with any system feature, replication does have its issues of concern. By its very
nature, replication is a location dependent function. Addresses of data copies must be stored and
kept up-to-date in order for any access to the replicas of the desired data. Another concern is that
when any change is made to either the original data source or one of its replicas, that change
must be reflected in all the other copies. This is not as simple a task as it may seem. If system
blocking is used to prevent multiple simultaneous accesses to a file on a single location, there
is the potential for indefinite blocking .
Cost of Replication
Along with the previously mentioned concerns, the cost of replicating data is also an item
for consideration. Not just what to charge, but how to charge and when. For example, is the fee
on a quantity of data replicated or on the length of time it took for the data to be replicated and
stored? What about a per replica charge? Are users charged an access fee? If so, are users
accessing replicas charged by the amount of data, number of replicas, or amount of time? Should
there be a charge if a replication fails?
Analysis of such question is defined as cost modeling and assists in determining value of
communications systems. It is possible to analyze data replication in a distributed computing
system with respect to minimizing the expected network cost incurred per transaction. Analysis
of a cost model can be determined many ways, but below is one of the more common methods.
Cost Model Analysis
V set of sites in a network
S set in question
R resident set
In the last decade there has been a push to decrease overall cost to operate on systems using
replication. One of the suggestions on how this can achieved is by charging for all transactions,
even unsuccessful ones, as a means of spread the cost over a larger area thereby reducing the per
transaction fee.
Significant Points
Based on my experience as a programmer analyst, it occurs to me that there might be yet another
way to handle the cost of replication. Consider a proportional costing scheme, where there are a
maximum number of flat fee transactions per file per server. After this maximum number of
accesses by the same server to the same file has been reached, an additional fee is applied to the
server until it acquires its own replica of the file. This scheme would ease the cost of replication
for users who maintain files well.
Summary
Data replication is the process of maintaining copies of data at multiple locations as a means of
decreasing the likelihood of inaccessibility during a system failure. The three main goals of
replication are accessibility, fault-tolerance, and consistency. Data transparency is also highly
desirable. There are two models of replication, passive and active. In either method there are five
steps for transaction completion: request, coordination, execution, agreement, and response.
Requests are sent from the clients through the front ends (which acts as an interfaces between the
clients and the replication managers) and on to the replication managers.

Você também pode gostar