0% found this document useful (0 votes)
18 views66 pages

Ruturaj DS

The document is a laboratory manual for the Distributed Systems course at Government Engineering College, Dahod, detailing the practical work and competencies expected from students. It includes certificates of completion, course outcomes, industry-relevant skills, guidelines for faculty and students, and safety instructions. The manual emphasizes hands-on experience and the development of practical skills in networking and programming through various experiments.

Uploaded by

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

Ruturaj DS

The document is a laboratory manual for the Distributed Systems course at Government Engineering College, Dahod, detailing the practical work and competencies expected from students. It includes certificates of completion, course outcomes, industry-relevant skills, guidelines for faculty and students, and safety instructions. The manual emphasizes hands-on experience and the development of practical skills in networking and programming through various experiments.

Uploaded by

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

A Laboratory Manual for

Distributed Systems
(3170719)

B.E. Semester 7 (Computer)

Government Engineering College, Dahod

Directorate of Technical Education, Gandhinagar,


Gujarat
Government Engineering College, Dahod
Department of Computer Engineering

Certificate

This is to certify that Mr./Ms. Ruturaj H. Solanki Enrollment No.


220183107024 of B.E. Semester 7th Computer Engineering of this Institute
has satisfactorily completed the Practical / Tutorial work for the subject
Distributed Systems (3170719) for the academic year 2022-23.

Place:
Date:

Name and Sign of


Faculty member
GOVERNMENT ENGINEERING COLLEGE DAHOD
Affiliated to GUJARAT TECHNOLOGICAL UNIVERSITY

COMPUTER ENGINEERING DEPARTMENT

CERTIFICATE
This is to certify that RUTURAJ HARENDRASINH SOLANKI bearing

enrollment number 220183107024 has satisfactorily completed the term work under

the program B.E. Computer Engineering of 7th semester

course Distributed Systems (3170719) for the academic term 2024-25.

Date of Submission

/ /

Sign of Faculty
Distributed System (3170719)

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome- based curriculum for engineering degree programs where sufficient weightage
is given to practical work. It shows importance of enhancement of skills amongst the students
and it pays attention to utilize every second of time allotted for practical amongst students,
instructors and faculty members to achieve relevant outcomes by performing the experiments
rather than having merely study type experiments. It is must for effective implementation of
competency focused outcome-based curriculum that every practical is keenly designed to serve
as a tool to develop and enhance relevant competency required by the various industry among
every student. These psychomotor skills are very difficult to develop through traditional chalk
and board content delivery method in the classroom. Accordingly, this lab manual is designed to
focus on the industry defined relevant outcomes, rather than old practice of conducting practical
to prove concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

A distributed system is a computing environment in which various components are spread across
multiple computers (or other computing devices) on a network. These devices split up the work,
coordinating their efforts to complete the job more efficiently than if a single device had been
responsible for the task. Distributed systems facilitate sharing different resources and
capabilities, to provide users with a single and integrated coherent network.

Utmost care has been taken while preparing this lab manual however always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal of
errors if an
Distributed System (3170719)

Programme Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and
receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Distributed System (3170719)

Practical – Course Outcome matrix

Course Outcomes (COs):


CO1: Understand the architecture and communication system in distributes systems.
CO2: Understand the synchronization and various election algorithms in distributed
systems.
CO3: Analyze various consistency and replication protocol and methods
CO4: Recognize security threats and apply cryptography methods for security
in distributed systems.
CO5: Understand various types of distributed systems.
Sr. CO CO CO CO CO
Objective(s) of Experiment
No. 1 2 3 4 5

1. Implement Chat Server application using Java √


Implement Remote Method Invocation (RMI) to find
2. whether number is odd or even. √

3. Implement Time Server using Remote Method √


Invocation (RMI).
Implement a program to print Hello Message using
4.
Remote Procedure Call (RPC)

Implement simple calculator using Remote Procedure
5 Call (RPC) √
To Simulate the functioning of Lamport’s Logical √
6.
clock.

7. To Simulate the functioning of Lamport’s Vector clock. √

8. Implement the functioning of Bully Algorithm. √


Implement client server application using CORBA √
9.

10. Implement a Simple Web service in Java. √

11. Creation of BPEL and composite application module √


12 Study of open source Key Management Tool √
Distributed System (3170719)

Industry Relevant Skills

The following industry relevant competency are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to develop web application using Netbeans/Ecllipse IDE
2. Will be able to do Network and distributed programming.

Guidelines for Faculty members


3. Teacher should provide the guideline with demonstration of practical to the students
with all features.
4. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
5. Involve all the students in performance of each experiment.
6. Teacher is expected to share the skills and competencies to be developed in the
students and ensure that the respective skills and competencies are developed in the
students after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students


9. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme,
skill set to be developed etc.
10. Students shall organize the work in the group and make record of all observations.
11. Students shall develop maintenance skill as expected by industries.
12. Student shall attempt to develop related hand-on skills and build confidence.
13. Student shall develop the habits of evolving more ideas, innovations, skills etc. apart from
those included in scope of manual.
14. Student shall refer technical magazines and data books.
15. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.

Common Safety Instructions


Students are expected to
1) switch on the PC carefully (not to use wet hands)
2) shutdown the PC properly at the end of your Lab
3) carefully Handle the peripherals (Mouse, Keyboard, Network cable etc)
4) Use Laptop in lab after getting permission from Teacher
Distributed System (3170719)

Index
(Progressive Assessment Sheet)

Sr. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar


No. No. perform submiss nt Teacher ks
ance ion Marks with date

1. Implement Chat Server application using Java

Implement Remote Method Invocation (RMI)


2. to find whether number is odd or even.

Implement Time Server using Remote Method


3.
Invocation (RMI).
Implement a program to print Hello Message
4.
using Remote Procedure Call (RPC)
Implement simple calculator using Remote
5 Procedure Call (RPC)

To Simulate the functioning of Lamport’s


6.
Logical clock.
To Simulate the functioning of Lamport’s
7.
Vector clock.
8. Implement the functioning of Bully Algorithm.

9. Implement client server application using


CORBA
10. Implement a simple web service in Java

Creation of BPEL and composite application


11.
module
12. Study of open source Key Management Tool

Total
Distributed System (3170719) 220183107024

Experiment No: 1

Implement Chat Server application using Java

Competency and Practical Skills: Networking & Programing Skill.

Relevant CO: CO1

Objective(s): (a). Learn Socket Programing in Java


(b). Learn the relation between Client and Server Application.

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans),

Theory:

A chat server application is a computer program that enables users to communicate with
each other over the internet or a network. Client-Server Model: A chat server application typically
follows a client-server model, where one or more clients connect to a central server. The server
manages the connections and the communication between the clients.

Safety and necessary Precautions:


1. Make sure the server/receiver program runs first
2. Handle all necessary compile time Exception

Procedure:

Implementing a chat server application in Java requires several steps, including setting up a server,
establishing client connections, handling client requests, and sending and receiving messages.
Here's a high-level algorithm for implementing a basic chat server application in Java:

3. Create a server socket that listens for incoming connections on a specific port number.
4. When a client connects, create a new socket to handle the client's requests and establish
input and output streams for sending and receiving messages.
5. Create a thread to handle each client connection so that multiple clients can connect and
communicate simultaneously.
4. Implement the logic for receiving and processing client requests, such as sending messages
to other clients or retrieving a list of currently connected clients.
5. Use synchronization to ensure that multiple threads do not modify shared resources (e.g. a
list of connected clients) at the same time.
6. When a client disconnects, remove it from the list of connected clients and close its socket.

6
Distributed System (3170719) 220183107024
Program Code:

//Server
import java.net.*;
import java.io.*;

public class
servertcp {
public static void main(String args[]) throws IOException
{ ServerSocket ss = new ServerSocket(5678);
System.out.println("Server is waiting for a connection...");
Socket s = ss.accept();
System.out.println("Connection from " + s);

PrintWriter pw1 = new PrintWriter(s.getOutputStream(),


true);
BufferedReader br3 = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedReader br4 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Server is ready");

String s1, s2;


while (true) {
s1 = br4.readLine();
pw1.println(s1);
if (s1.equals("over")) {
break;
}
s2 = br3.readLine();
System.out.println("Client: " + s2);
if (s2.equals("over")) {
break;
}
}

s.close();
ss.close();
}
} //server ends

// Client
import java.net.*;
import java.io.*;

public class
clienttcp{
public static void main(String args[]) throws IOException
{ Socket cc = new Socket(InetAddress.getLocalHost(), 5678);
PrintWriter pw = new PrintWriter(cc.getOutputStream(), true);
BufferedReader br1 = new BufferedReader(new InputStreamReader(cc.getInputStream()));
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));

String str1, str2;


while (true) {
str1 = br1.readLine(); 7
System.out.println("Server: " + str1);
if (str1.equals("over")) {
Distributed System (3170719) 220183107024
break;
}
str2 = br2.readLine();
pw.println(str2);
if (str2.equals("over")) {
break;
}
}

cc.close();
}
} //client ends

Conclusion:

Exercise:

1. What is the role of socket class in Java for client server programing?
Ans: In Java, the Socket class plays a crucial role in client-server programming by enabling
communication between two endpoints over a network. Specifically, it is used for establishing a
connection from a client to a server or from one server to another.

Here's a breakdown of its key functionalities:

Socket Creation:

The Socket class is responsible for creating a socket, which is a combination of an IP address and a
port number. It represents one endpoint of a network communication channel.
Connecting to a Server:

In a client-server scenario, the client uses a Socket to initiate a connection with a server. The client
provides the IP address and port number of the server it wants to connect to.
Data Transfer:

Once a connection is established, the Socket provides input and output streams (InputStream and
OutputStream) that allow for data transfer between the client and the server.
Blocking and Non-blocking Operations:

8
Distributed System (3170719) 220183107024
Sockets can be used for both blocking and non-blocking I/O operations. In blocking mode, operations
on the socket will block until they can complete. In non-blocking mode, operations may not complete
immediately, allowing for more flexibility in handling multiple connections.
Socket Types:

Java supports both TCP and UDP protocols, and the Socket class can be used for both. For TCP, you'd
use Socket for reliable, connection-oriented communication. For UDP, you'd use DatagramSocket for
connectionless communication.
Closing the Connection:

Once communication is complete, both the client and server should close their respective sockets
using the close() method. This releases system resources associated with the socket.
Error Handling:

The Socket class also provides methods to handle various exceptions that might occur during socket
operations, such as IOException.
In summary, the Socket class in Java is fundamental for establishing network connections between
clients and servers. It facilitates data exchange between endpoints and offers flexibility in terms of
blocking and non-blocking operations, as well as support for both TCP and UDP protocols.

2. What method in Java can be used by a client program to establish a connection to a server
program?
a. Socket.accept()
b. ServerSocket.bind()
c. Socket.connect()
d.ServerSocket.accept()
Ans: Socket.connect()

Suggested References:
3. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
4. "TCP/IP Sockets in Java: Practical Guide for Programmers" by Kenneth L. Calvert and Michael J.
Donahoo.
3. Distributed Computing and application by M L Liu, Pearson Education Inc.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

9
Distributed System (3170719) 220183107024

Experiment No: 2

Implement Remote Method Invocation (RMI) in java to find whether number is odd or
even

Competency and Practical Skills: Networking & Programing Skill.

Relevant CO: CO1

Objective(s): (a) Learn to develop distributed application using RMI in Java.


(b) Learn how to implement interfaces, stubs, and skeletons for RMI objects.

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans), RMI


framework

Theory:
Remote Method Invocation (RMI) is a Java-based technology that enables communication
between different Java Virtual Machines (JVMs) running on different hosts in a network. RMI
provides a mechanism for invoking methods on objects that reside in different JVMs, making it
possible to implement distributed applications in Java.

The basic idea behind RMI is that a Java object running in one JVM can invoke methods
on a Java object running in another JVM. To achieve this, the Java objects that can be accessed
remotely must implement a special interface, called a Remote interface, which extends the
java.rmi.Remote interface. This interface serves as a marker, indicating that the object can be
accessed remotely.

To use RMI, the client needs to know the name or reference of the remote object it wants to
invoke. This can be done by registering the object with a naming service, such as the Java Naming
and Directory Interface (JNDI). Once the client has obtained a reference to the remote object, it
can invoke methods on the object as if it were a local object.

Using RMI you have to implement a program which will find whether the number is odd
or even.

Safety and necessary Precautions:


1. Make sure the server/receiver program runs first
2. Handle all necessary compile time Exception

Procedure:

3. Define the Remote Interface: Create a remote interface, let's call it OddEvenInterface,
which declares the method signatures that will be used to determine if a number is even or
odd. This interface should extend Remote.

4. Implement the Remote Interface: Implement the OddEvenInterface interface in a class


that will be used as a remote object. Let's call it OddEvenServer. This class must extend
UnicastRemoteObject and provide an implementation for the remote methods.

5. Create the RMI Registry: Start the RMI registry on the host where the remote object will
be running. This can be done using the rmiregistry command.
10
Distributed System (3170719) 220183107024
4. Register the Remote Object: Register the remote object with the RMI registry using the
Naming.rebind() method. The name of the object that is used in the Naming.rebind()
method is the name that the client will use to access the remote object.

5. Create the RMI Client: Create a client program that will use the remote object to determine
if a number is even or odd. The client must look up the remote object in the RMI registry
using the Naming.lookup() method.

6. Compile and Run: Compile both the server and client classes and run the server first,
followed by the client. The output should indicate whether the number is even or odd.

Program Code:

Sample Program : (Students can frame it in their own way)

Interface:-

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class NumberCheckerImpl extends UnicastRemoteObject implements NumberChecker {


protected NumberCheckerImpl() throws RemoteException {
super();
}

@Override
public boolean isEven(int number) throws RemoteException {
return number % 2 == 0;
}
}
Server:-

// NumberCheckerServer.java
import java.rmi.Naming;
import
java.rmi.registry.LocateRegist
ry;

public class NumberCheckerServer


{ public static void main(String[]
args) {
try {
NumberChecker checker = new NumberCheckerImpl();
LocateRegistry.createRegistry(1234); // Default RMI registry port

// Bind the remote object's stub in the registry


Naming.rebind("NumberChecker", checker);

System.out.println("NumberChecker Server is
ready.");
} catch (Exception e) {
System.err.println("NumberChecker Server exception: " + e.toString());
e.printStackTrace();
} 11
}
}
Distributed System (3170719) 220183107024
Client:-

// NumberCheckerClient.java
import java.rmi.Naming;

public class NumberCheckerClient


{ public static void main(String[]
args) {
try {
NumberChecker checker = (NumberChecker)
Naming.lookup("rmi://localhost/NumberChecker");
int number = 5;

if (checker.isEven(number))
{ System.out.println(number + " is
even.");
} else {
System.out.println(number + " is odd.");
}
} catch (Exception e) {
System.err.println("NumberCheckerClient exception: " + e.toString());
e.printStackTrace();
}
}
}

Conclusion:

Exercise :

1. What does RMI stand for?


a) Remote Method Invocation
b) Remote Method Interface
c) Remote Method Implementation
d)Remote Method Integration
Ans: Remote Method Invocation

2. Which interface must a remote


object implement in order to be
accessed remotely?
a) java.rmi.Remote
b) java.rmi.Server
c) java.rmi.Client
d)java.rmi.RemoteObject
Ans: java.rmi.Remote

3. What is the purpose of a


naming service in RMI?
a) To provide a registry
for remote objects 12
b) To serialize Java
objects
Distributed System (3170719) 220183107024
Ans: To provide a registry for remote objects

Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Java RMI" by William Grosso.
3. Distributed Computing and application by M L Liu, Pearson Education Inc.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

13
Distributed System (3170719) 220183107024

Experiment No: 3

Implement Timer Server using Remote Method Invocation (RMI) in java

Competency and Practical Skills: Network programing & Programing Skill.

Relevant CO: CO1

Objectives: (a) Learn to develop distributed application using RMI in Java.


(b) Learn how to implement interfaces, stubs, and skeletons for RMI objects.

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans), RMI


framework

Theory:
Remote Method Invocation (RMI) is a Java-based technology that enables communication
between different Java Virtual Machines (JVMs) running on different hosts in a network. RMI
provides a mechanism for invoking methods on objects that reside in different JVMs, making it
possible to implement distributed applications in Java.

The basic idea behind RMI is that a Java object running in one JVM can invoke methods
on a Java object running in another JVM. To achieve this, the Java objects that can be accessed
remotely must implement a special interface, called a Remote interface, which extends the
java.rmi.Remote interface. This interface serves as a marker, indicating that the object can be
accessed remotely.

To use RMI, the client needs to know the name or reference of the remote object it wants to
invoke. This can be done by registering the object with a naming service, such as the Java Naming
and Directory Interface (JNDI). Once the client has obtained a reference to the remote object, it
can invoke methods on the object as if it were a local object.

A Timer server is a type of server that provides time synchronization services to clients. It
is often used in distributed systems where it is important for all machines to have a consistent view
of time.

To implement a Timer server in Java, you can use the Java Timer class and the RMI
(Remote Method Invocation) framework.

Safety and necessary Precautions:


1. Make sure the server/receiver program runs first
2. Handle all necessary compile time Exception

Procedure:

3. Define the remote interface: Define a remote interface that extends the java.rmi.Remote
interface and declares the methods that the server will provide. In this case, you need to
define a method that returns the current time.

4. Implement the remote interface: Implement the remote interface in a server class that
14
Distributed System (3170719) 220183107024
extends the java.rmi.server.UnicastRemoteObject class. This class should provide an
implementation of the getTime() method.

3. Create the server: Create a server class that creates an instance of the TimeServerImpl class
and binds it to the RMI registry.
4. Create the client: Create a client class that looks up the TimeServer object in the RMI
registry and calls its getTime() method.

5. Run the server and client: Start the server class first and then start the client class. The
client should display the current time obtained from the server.

Program Code:
Interface:
// TimerServerImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Date;

public class TimerServerImpl extends UnicastRemoteObject implements TimerServer {


protected TimerServerImpl() throws RemoteException {
super();
}

@Override
public long getCurrentTime() throws RemoteException {
return new Date().getTime();
}
}
Server:
// TimerServerServer.java
import java.rmi.Naming;
import
java.rmi.registry.LocateR
egistry;

public class
TimerServerServer {
public static void main(String[] args) {
try {
TimerServer timer = new TimerServerImpl();
LocateRegistry.createRegistry(1234); // Default RMI registry port

// Bind the remote object's stub in the registry


Naming.rebind("TimerServer", timer);

System.out.println("TimerServer Server is
ready.");
} catch (Exception e) {
System.err.println("TimerServer Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client: 15
// TimerServerClient.java
import java.rmi.Naming;
Distributed System (3170719) 220183107024
public class TimerServerClient {
public static void main(String[] args) {
try {
TimerServer timer = (TimerServer) Naming.lookup("rmi://localhost/TimerServer");

long currentTime = timer.getCurrentTime();


System.out.println("Current time in milliseconds: " + currentTime);
} catch (Exception e) {
System.err.println("TimerServerClient exception: " + e.toString());
e.printStackTrace();
}
}
}

Conclusion:

Exercise:
1. What is skeleton in RMI?
Ans: In RMI (Remote Method Invocation), a skeleton is a server-side object responsible for
dispatching incoming remote method invocations to the actual remote object's implementation.
It acts as an intermediary between the client and the actual remote object.

Here's how it works:

When a client makes a remote method call, it creates a stub (client-side proxy) for the remote
object. This stub resides on the client-side and is used to invoke methods on the remote object.

The stub, being on the client-side, communicates with the server-side skeleton.

The skeleton receives the method call from the stub and then forwards it to the actual remote
object that resides in the server's memory.

The remote object executes the method, and the result (if any) is returned back to the skeleton.

The skeleton sends the result back to the client via the network.

The purpose of the skeleton is to manage the communication between the client and the server,
allowing the client to invoke methods on the remote object as if it were a local object.

It's important to note that the concept of a skeleton was more significant in earlier versions of
Java RMI (prior to Java 5). In modern Java RMI, stubs and skeletons are generated
dynamically
16
Distributed System (3170719) 220183107024
at runtime, so developers typically don't need to deal with the specifics of skeleton
implementation.

2. What is Registry in RMI?


Ans: In RMI (Remote Method Invocation), a registry is a service that allows objects to be
bound to names and then looked up by clients. It serves as a simple, distributed directory
service where remote objects can be registered and later retrieved by other programs.

Here are the key points about the RMI Registry:

Naming and Binding:

The RMI registry provides a way to associate a name with a remote object. This allows clients
to look up the object using its name rather than its network address.
Centralized Service:

The RMI registry is a centralized service that runs on a designated host and a specific port
(usually port 1099 by default).
Registration:

Remote objects must be explicitly registered with the RMI registry by binding them to a name.
This is typically done by the server program.
Lookup:

Clients can then look up the remote object by its name using the registry's lookup method.
Unbinding:

If a remote object is no longer needed, it can be unbound from the registry, effectively
removing its association with the name.
Rebinding:

If necessary, a remote object can be rebound to a different name in the registry.


Serving Multiple Clients:

The RMI registry can serve multiple clients simultaneously, allowing different programs to
register and look up remote objects.
Registry Creation:

The RMI registry can be created using the java.rmi.registry.LocateRegistry class.


java
Copy code
LocateRegistry.createRegistry(1099); // Default port is 1099
Security Considerations:

The RMI registry can be configured with access control policies to control which clients are
allowed to bind and look up objects.
Alternative Naming Services:

While the RMI registry is the most common naming service, it's also possible to use alternative
naming services, such as LDAP or custom naming services.
In summary, the RMI registry provides a convenient way for remote objects to be located by
their names rather than requiring clients to know their network details. It acts as a directory
service for remote objects in an RMI application.
3. How does RMI enable remote invocation of methods?
a) By creating a proxy object that implements the remote interface of the remote object
17
Distributed System (3170719) 220183107024
b) By sending a serialized copy of the remote object to the client
c) By opening a socket connection between the client and server
d) By invoking methods on the remote object directly
Ans: By creating a proxy object that implements the remote interface of the remote object

Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. Distributed Computing and application by M L Liu, Pearson Education Inc.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

18
Distributed System (3170719) 220183107024
Experiment No: 4

Implement a program which print Hello Message using Remote Procedure Call (RPC)

Competency and Practical Skills: Network programing & Programing Skill.

Relevant CO: CO1

Objectives: (a)To understand the concept of Remote Procedure Call (RPC) and its
implementation in Java.
(b) To create a simple Java program that demonstrates the use of RPC.

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans), RMI


framework.

Theory:
Remote Procedure Call (RPC) is a technique used to enable programs to call procedures on
remote computers as if they were local procedures. It allows a program to invoke a procedure on a
remote computer using the same syntax as for local procedure calls. The RPC program consists of
a client program that sends a request to a server program to execute a procedure, and the server
program executes the procedure and sends a response back to the client.

Safety and necessary Precautions:


3. Make sure the server/receiver program runs first
4. Handle all necessary compile time Exception

Procedure:
Here's a steps for printing a "Hello" message using Remote Procedure Call (RPC) in Java:

5. Set up your development environment:

 Install the latest version of Java Development Kit (JDK) and NetBeans IDE (or
your preferred IDE).
 Create a new Java project in NetBeans.
6. Define the interface for the remote procedure:
Create a new Java interface called HelloService.
Define a single method in the interface called sayHello() that returns a String.
Annotate the method with the @Remote annotation from the javax.ejb package to
indicate that it is a remote method.
 Save the interface.
7. Implement the remote procedure:
Create a new Java class called HelloServiceImpl.
Implement the sayHello() method by returning the string "Hello, world!".
Annotate the class with the @Stateless annotation from the javax.ejb package to
indicate that it is a stateless session bean.
 Save the class.
8. Deploy the remote procedure:
 Right-click on the project in NetBeans and select "Clean and Build".
 Right-click on the project again and select "Deploy".
9. Create the client application:
19
Distributed System (3170719) 220183107024

 Create a new Java class called HelloClient.


 Add a main method to the class.
 Use the InitialContext class to look up the remote HelloService object.
 Call the sayHello() method on the remote object and print the result to the console.
 Save the class.
6. Run the client application:
 Right-click on the HelloClient class and select "Run File".
 Check the console output to see if the "Hello, world!" message was printed.

Program Code:
Interface:
// HelloServiceImpl.java
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class HelloServiceImpl extends UnicastRemoteObject implements HelloService {


protected HelloServiceImpl() throws RemoteException {
super();
}

@Override
public String getHelloMessage() throws RemoteException {
return "Hello from Server!";
}
}
Server:
// HelloServer.java
import java.rmi.Naming;

public class HelloServer


{
public static void main(String[] args) {
try {
HelloService helloService = new
HelloServiceImpl();

// Bind the remote object's stub in the registry


Naming.rebind("HelloService", helloService);

System.out.println("HelloService Server is
ready.");
} catch (Exception e) {
System.err.println("HelloService Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client:
//public class HelloClient {
HelloClient.java
public
import static void main(String[] args) {
java.rmi.Naming;
try {
HelloService = (HelloService)
20
helloService
Distributed System (3170719) 220183107024
Naming.lookup("rmi://localhost/HelloService");

String message = helloService.getHelloMessage();


System.out.println("Message from Server: " + message);
} catch (Exception e) {
System.err.println("HelloClient exception: " + e.toString());
e.printStackTrace();
}
}
}

Conclusion:

Exercise:
1. What is Remote Procedure Call (RPC)?
Ans: Remote Procedure Call (RPC) is a protocol that allows a program to execute procedures or
functions on a remote server as if they were local. It enables distributed computing by allowing
programs to invoke methods or procedures on remote servers over a network.

Key features of RPC include:

Abstraction of Network Communication:

RPC hides the complexities of network communication, allowing developers to call remote
methods in a manner similar to local method calls.
Client-Server Model:

RPC follows a client-server model where a client program makes a procedure call that gets
executed on a remote server.
Stubs and Skeletons:

In early implementations of RPC, stubs (client-side) and skeletons (server-side) were manually
coded to handle the communication details. Modern RPC frameworks generate these components
automatically.
Serialization and Deserialization:

Parameters and return values of remote method calls are typically serialized (converted to a format
suitable for transmission over a network) and then deserialized on the receiving end.
Synchronous Communication:

Traditional RPC systems are synchronous, meaning the client blocks until the remote procedure
call is completed. Some advanced RPC systems support asynchronous communication as well.
Error Handling:

21
Distributed System (3170719) 220183107024

RPC mechanisms include provisions for handling errors and exceptions that occur during remote
method invocation.
Transparency:

RPC aims to provide transparency to the calling program, making it unaware that it is invoking a
remote procedure rather than a local one.
Language Independence:

RPC systems are designed to work across different programming languages, allowing programs
written in one language to call procedures written in another.
Interoperability:

RPC allows programs running on different platforms and operating systems to communicate and
work together seamlessly.
Examples of RPC implementations include Java RMI (Remote Method Invocation), Microsoft's
DCOM (Distributed Component Object Model), and ONC RPC used in the NFS (Network File
System) protocol.

Overall, RPC is a powerful mechanism for building distributed applications, enabling components
on different machines to work together as if they were part of a single program.

2. Which framework is a popular choice for implementing RPC in Java?


Ans: A popular choice for implementing Remote Procedure Call (RPC) in Java is the Java RMI
(Remote Method Invocation) framework. Java RMI is a built-in feature of the Java programming
language and provides a straightforward way to invoke methods on remote objects.

Java RMI offers the following features:

Easy Integration with Java:

Java RMI is seamlessly integrated into the Java language and platform, making it a natural choice
for Java-based distributed applications.
Automatic Stub and Skeleton Generation:

Java RMI automatically generates stubs (client-side proxies) and skeletons (server-side
dispatchers) for remote objects, which simplifies the development process.
Support for Object Serialization:

Java RMI handles the serialization and deserialization of objects, allowing complex data structures
to be passed between the client and server.
Garbage Collection:

Java RMI supports automatic garbage collection of remote objects, making memory management
more convenient for distributed systems.
Dynamic Class Loading:

Java RMI allows for dynamic class loading, which enables the server to send class definitions to
the client if needed.
Security and Access Control:

Java RMI provides mechanisms for authentication, authorization, and access control, allowing
developers to secure their distributed applications.
Exception Handling:

22
Distributed System (3170719) 220183107024
Java RMI handles exceptions that occur during remote method invocation, allowing for graceful
error handling.
Asynchronous Invocation:

While traditional Java RMI is synchronous, it's possible to implement asynchronous


communication using additional techniques or libraries.
Language Neutrality:

While Java RMI is primarily designed for Java-to-Java communication, it's possible to integrate
with other languages using technologies like CORBA (Common Object Request Broker
Architecture).
Overall, Java RMI is a powerful and widely used framework for building distributed applications
in Java. It provides the necessary tools and abstractions to facilitate remote method invocation
between Java objects on different machines.

3. What are some important factors to consider when implementing RPC in Java?
Ans: A popular choice for implementing Remote Procedure Call (RPC) in Java is the Java RMI
(Remote Method Invocation) framework. Java RMI is a built-in feature of the Java programming
language and provides a straightforward way to invoke methods on remote objects.

Java RMI offers the following features:

Easy Integration with Java:

Java RMI is seamlessly integrated into the Java language and platform, making it a natural choice
for Java-based distributed applications.
Automatic Stub and Skeleton Generation:

Java RMI automatically generates stubs (client-side proxies) and skeletons (server-side
dispatchers) for remote objects, which simplifies the development process.
Support for Object Serialization:

Java RMI handles the serialization and deserialization of objects, allowing complex data structures
to be passed between the client and server.
Garbage Collection:

Java RMI supports automatic garbage collection of remote objects, making memory management
more convenient for distributed systems.
Dynamic Class Loading:

Java RMI allows for dynamic class loading, which enables the server to send class definitions to
the client if needed.
Security and Access Control:

Java RMI provides mechanisms for authentication, authorization, and access control, allowing
developers to secure their distributed applications.
Exception Handling:

Java RMI handles exceptions that occur during remote method invocation, allowing for graceful
error handling.
Asynchronous Invocation:

While traditional Java RMI is synchronous, it's possible to implement asynchronous


communication using additional techniques or libraries.
Language Neutrality:
23
Distributed System (3170719) 220183107024

While Java RMI is primarily designed for Java-to-Java communication, it's possible to integrate
with other languages using technologies like CORBA (Common Object Request Broker
Architecture).
Overall, Java RMI is a powerful and widely used framework for building distributed applications
in Java. It provides the necessary tools and abstractions to facilitate remote method invocation
between
Java objects on different machines.

User
3. What are some important factors to consider when implementing RPC in Java?
ChatGPT
When implementing Remote Procedure Call (RPC) in Java, there are several important factors to
consider to ensure the successful development and deployment of distributed applications. Here
are
some key considerations:

Interface Definition:

Define clear and well-documented interfaces for your remote objects. This includes specifying the
methods that can be invoked remotely and any exceptions that may be thrown.
Object Serialization:

Ensure that the objects being passed between the client and server are serializable. This allows
them to be converted to a format suitable for transmission over the network.
Error Handling:

Implement appropriate error handling and exception management for remote method invocations.
This includes handling network errors, server-side exceptions, and other potential issues.
Security:

Consider security measures such as authentication, authorization, encryption, and access control.
Implement security mechanisms to protect sensitive data and prevent unauthorized access.
Garbage Collection and Object Lifetime:

Understand how remote objects are managed in terms of garbage collection. Consider whether
objects should be kept alive on the server or whether they can be garbage collected.
Concurrency and Thread Safety:

Design your remote objects to be thread-safe if they will be accessed by multiple clients
concurrently. Implement synchronization or other concurrency control mechanisms as needed.
Performance Optimization:

Optimize the performance of your RPC system by minimizing network round-trips, reducing
object serialization overhead, and considering the use of batched or asynchronous invocations
where appropriate.
Stub and Skeleton Generation:

Familiarize yourself with how stubs (client-side proxies) and skeletons (server-side dispatchers) are
generated and how they interact with your remote objects.
Versioning and Compatibility:

Consider how changes to the interfaces of your remote objects may impact existing clients. Plan
for versioning and backward compatibility strategies.
24
Distributed System (3170719) 220183107024
Timeouts and Retries:

Implement timeouts to handle situations where a remote call takes too long. Consider adding retry
logic for robustness in the face of network or server failures.
Testing and Debugging:

Develop a robust testing strategy, including unit tests for individual components, as well as
integration tests for the entire distributed system. Use debugging tools and techniques to
troubleshoot issues.
Monitoring and Logging:

Implement logging and monitoring to track the behavior of your distributed system. This includes
recording remote method invocations, tracking performance metrics, and monitoring for errors or
exceptions.
By considering these factors, you can design and implement an effective RPC system in Java that
meets the requirements of your distributed application while ensuring reliability, security, and
performance.

Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. Distributed Computing and application by M L Liu, Pearson Education Inc.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

25
Distributed System (3170719) 220183107024
Experiment No: 5

Implement simple calculator using Remote Procedure Call (RPC)

Competency and Practical Skills: Network programing & Programing Skill.

Relevant CO: CO1

Objectives: (a). To implement remote procedure call (RPC) in Java


(b). To perform basic arithmetic operations using RPC
(c). To understand the concept of remote method
invocation
Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans), RMI
framework

Theory:
Remote Procedure Call (RPC) is a technique used to enable programs to call procedures on
remote computers as if they were local procedures. It allows a program to invoke a procedure on a
remote computer using the same syntax as for local procedure calls. The RPC program consists of
a client program that sends a request to a server program to execute a procedure, and the server
program executes the procedure and sends a response back to the client.
In this experiment, we will use RPC to implement a simple calculator program that
performs basic arithmetic operations such as addition, subtraction, multiplication, and division.

Safety and necessary Precautions:


1. Make sure the server/receiver program runs first
2. Handle all necessary compile time Exception

Procedure:

Here's a step-by-step procedure to implement a simple calculator using Remote Procedure Call
(RPC) in Java:
3. Set up your development environment:
 Install the latest version of Java Development Kit (JDK) and NetBeans IDE (or
your preferred IDE).
 Create a new Java project in NetBeans.

4. Define the interface for the remote procedure:


 Create a new Java interface called CalculatorService.
 Define methods in the interface for the basic arithmetic operations such as add(),
subtract(), multiply(), and divide().
 Annotate the methods with the @Remote annotation from the javax.ejb package to
indicate that they are remote methods.
 Save the interface.

5. Implement the remote procedure:


 Create a new Java class called CalculatorServiceImpl.
 Implement the add(), subtract(), multiply(), and divide() methods by performing the
respective arithmetic operations on the input parameters.
 Annotate the class with the @Stateless annotation from the javax.ejb package to
indicate that it is a stateless session bean.
 Save the class.
6. Deploy the remote procedure:
26
Distributed System (3170719) 220183107024
 Right-click on the project in NetBeans and select "Clean and Build".
 Right-click on the project again and select "Deploy".

5. Create the client application:


 Create a new Java class called CalculatorClient
 Add a main method to the class.
 Use the InitialContext class to look up the remote CalculatorService object.
 Call the add(), subtract(), multiply(), and divide() methods on the remote object and
print the results to the console
• Save the class.

6. Run the client application:


 Right-click on the CalculatorClient class and select "Run File". • Check the console
output to see if the arithmetic operations were performed correctly.
.
Program Code:
Interface:
//
CalculatorImpl.j
ava
import
java.rmi.Remote
Exception;
import
java.rmi.server.
UnicastRemote
Object;

public class CalculatorImpl extends UnicastRemoteObject implements Calculator {


protected CalculatorImpl() throws RemoteException {
super();
}

@Override
public int add(int a, int b) throws RemoteException {
return a + b;
}

@Override
public int subtract(int a, int b) throws RemoteException {
return a - b;
}

@Override
public int multiply(int a, int b) throws RemoteException {
return a * b;
}

@Override
public int divide(int a, int b) throws RemoteException {
if (b != 0) {
return a / b;
} else {
throw new ArithmeticException("Division by zero");
}
} 27
}
Server:
Distributed System (3170719) 220183107024
public class CalculatorServer {
public static void main(String[] args) {
try {
Calculator calculator = new
CalculatorImpl();
// Bind the remote object's stub in the registry
Naming.rebind("Calculator", calculator);

System.out.println("Calculator Server is
ready.");
} catch (Exception e) {
System.err.println("Calculator Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client:
// CalculatorClient.java
import java.rmi.Naming;

public class
CalculatorClient {
public static void main(String[] args) {
try {
Calculator calculator = (Calculator)
Naming.lookup("rmi://localhost/
Calculator");

int a = 10;
int b = 5;

System.out.println("Sum: " + calculator.add(a, b));


System.out.println("Difference: " + calculator.subtract(a, b));
System.out.println("Product: " + calculator.multiply(a, b));
System.out.println("Quotient: " + calculator.divide(a, b));
} catch (Exception e) {
System.err.println("CalculatorClient exception: " + e.toString());
e.printStackTrace();
}
}
}

Conclusion:

28
Distributed System (3170719) 220183107024
Exercise:

1. What are the advantages of using RPC?


Ans: Using Remote Procedure Call (RPC) offers several advantages for building distributed
systems:
Abstraction of Network Communication:
RPC hides the complexities of network communication, allowing developers to focus on the
logic of the remote method calls rather than low-level networking details.
Simplicity and Familiarity:
RPC programming models are similar to local method invocations, making it easier for
developers to understand and use.
Language Neutrality:
RPC allows programs written in different languages to communicate with each other, enabling
interoperability between systems built on different platforms or using different programming
languages.
Code Reusability:
RPC allows for the reuse of existing code by enabling methods in one program to be called
from another program, even if they are running on separate machines.
Location Transparency:
With RPC, the calling program is unaware of whether the method is being executed locally or
on a remote machine. This provides a level of transparency to the client.
Synchronization and Concurrency:
RPC systems often handle synchronization and concurrency automatically, making it easier to
build multi-threaded or concurrent applications.
Structured Programming:
RPC encourages a structured approach to designing distributed systems, where components
interact through well-defined interfaces, leading to more maintainable and organized code.
Error Handling:
RPC frameworks typically provide mechanisms for handling errors and exceptions that occur
during remote method invocation, making it easier to manage failures in a distributed
environment.
Security Integration:
Many RPC frameworks offer security features, such as encryption and authentication, to
protect data during transit over the network.
Scalability:
RPC systems can be designed to scale by distributing the load across multiple servers,
allowing for the handling of a large number of client requests.
Code Modularization:

29
Distributed System (3170719) 220183107024
RPC encourages modularization of code, as services can be implemented as separate modules
or services, making it easier to manage and update individual components.
Fault Tolerance:
Some advanced RPC systems provide mechanisms for fault tolerance, allowing for the
recovery from errors or failures in the network or server.
Overall, RPC provides a powerful and flexible mechanism for building distributed systems,
enabling programs on different machines to work together seamlessly. It simplifies the
development process and allows for the integration of components written in different
languages, making it a valuable tool for building modern distributed applications.

2. How does RPC enable distributed computing?


Ans: RPC (Remote Procedure Call) enables distributed computing by allowing programs to
invoke procedures or functions on remote servers as if they were local. Here's how RPC
facilitates distributed computing:
Abstraction of Network Communication:
RPC abstracts away the complexities of network communication. It provides a programming
model that is similar to invoking local procedures, making it easier for developers to work with
distributed systems.
Client-Server Interaction:

In an RPC system, there are typically two components: the client and the server. The client
makes a procedure call that gets executed on a remote server.
Interface Definition:
RPC requires the definition of interfaces that specify the methods or procedures that can be
invoked remotely. These interfaces serve as contracts between the client and server.
Marshalling and Unmarshalling:
Before sending parameters to the remote server, RPC systems serialize (marshal) them into a
format suitable for network transmission. On the server side, the parameters are deserialized
(unmarshaled) back into their original form.
Stubs and Skeletons:
In early implementations of RPC, stubs (client-side proxies) and skeletons (server-side
dispatchers) were manually coded to handle the communication details. Modern RPC
frameworks generate these components automatically.
Network Transport:
RPC mechanisms handle the network transport, including establishing connections, sending
data packets, and managing sockets. This allows the client and server to communicate over a
network.
Remote Procedure Invocation:

30
Distributed System (3170719) 220183107024
When the client makes a remote procedure call, it appears as a regular method call in the
client's code. The RPC system takes care of packaging the method parameters and sending
them to the server.
Server Execution:
The server receives the remote procedure call, looks up the corresponding procedure
implementation, and executes it as if it were a local method.
Result Transmission:
After the server executes the procedure, it sends back the result to the client using the same
RPC mechanism. The result is then unmarshaled and made available to the client program.
Transparency:
RPC aims to provide transparency to the calling program, meaning that the client is unaware
that it is invoking a remote procedure rather than a local one. This simplifies the development
process.
Error Handling:
RPC systems include provisions for handling errors and exceptions that occur during remote
method invocation. This ensures that the client can gracefully handle failures or unexpected
conditions.
Language Neutrality:
While RPC is commonly used in environments where both the client and server are written in
the same language, it can also be used to facilitate communication between programs written in
different languages.
By providing a high-level abstraction for remote communication, RPC enables developers to
build distributed applications more easily, allowing components on different machines to work
together seamlessly.

3. What is the role of the client program in an RPC system?


Ans: In an RPC (Remote Procedure Call) system, the client program plays a crucial role in
initiating and managing the remote procedure calls. Here are the key responsibilities and roles
of the client program in an RPC system:
Initiating Remote Procedure Calls (RPCs):
The primary role of the client program is to initiate remote procedure calls to the server. This is
achieved by invoking methods on proxy objects or stubs that represent the remote services.
Creating Stubs (Proxy Objects):
The client program typically uses a tool or library provided by the RPC framework to generate
stubs. Stubs act as local proxies for the remote services, allowing the client to invoke methods
on them as if they were local.
Marshalling Parameters:
Before making an RPC, the client marshals (serializes) the parameters of the remote method
into a format suitable for network transmission. This involves converting the parameters into a
standardized data representation.

31
Distributed System (3170719) 220183107024
Establishing Network Connections:
The client program is responsible for establishing network connections with the remote server.
This may involve creating and managing sockets or using higher-level network communication
protocols.
Transmitting RPC Requests:
Once the parameters are marshaled and the connection is established, the client sends the RPC
request to the server. This request includes information about the remote method to be invoked
and the associated parameters.
Managing Timeouts and Retries:
The client may implement mechanisms to handle timeouts in case the server takes too long to
respond. Additionally, the client may implement retry logic to resend the request in case of
network failures.
Handling Error Responses:
The client is responsible for handling any error responses or exceptions that may occur during
the remote procedure call. This includes network errors, server-side exceptions, and other
potential issues.
Unmarshalling Results:
Once the server processes the RPC request and returns a result, the client unmarshals
(deserializes) the result to obtain the return values of the remote method.
Providing Callbacks (if applicable):

In certain cases, the client may need to provide callback functions or methods that the server
can use to notify the client of events or updates.
Implementing Business Logic:
In addition to managing RPC-related tasks, the client program also contains the business logic
and application-specific code that determines when and how to initiate remote calls.
Coordinating Multiple RPCs (if applicable):
In some scenarios, the client may need to coordinate multiple RPCs, possibly in a specific
order or as part of a larger transaction.
Ensuring Security (if applicable):
The client may be responsible for implementing security measures, such as encryption,
authentication, and access control, depending on the requirements of the application.
Overall, the client program acts as the initiator and manager of remote procedure calls,
enabling it to interact with remote services provided by the server. It plays a central role in the
communication between the client and the server in an RPC system.

32
Distributed System (3170719) 220183107024
Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Java RMI" by William Grosso
3. Distributed Computing and application by M L Liu, Pearson Education Inc.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

33
Distributed System (3170719) 220183107024

Experiment No: 6

Implementation of Lamport's logical Clock Algorithm for Distributed Systems

Competency and Practical Skills: Network Programming & Programming Skill

Relevant CO: CO2

Objectives: 1. Understand the Lamport algorithm for logical clocks.


2. Implement the Lamport algorithm using Java programming language.
3. Test the Lamport algorithm to order events in a distributed system.

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans)

Theory:

The Lamport algorithm is a logical clock algorithm that allows ordering of events in a
distributed system. The algorithm was proposed by Leslie Lamport in 1978.

The algorithm works by assigning a logical clock value to each event in the system. The
logical clock is a virtual clock that is incremented each time an event occurs in the system. The
logical clock value of an event is the timestamp of the event.

The Lamport algorithm ensures that the events are ordered based on their logical clock
values. If event A has a lower logical clock value than event B, then event A occurred before event
B.

The algorithm is implemented using a message passing mechanism. When a process sends
a message to another process, it includes its current logical clock value in the message. When the
receiving process receives the message, it updates its own logical clock value to the maximum of
its current value and the value received in the message. This ensures that the logical clock values
of events are monotonically increasing.

Safety and necessary Precautions: Handle all necessary compile time Exceptions.

Procedure:

1. Define the Event class: Define an Event class that stores the timestamp and the process id
of an event.

2. Define the Process class: Define a Process class that simulates a process in the distributed
system. The Process class should contain a logical clock value and a queue of events that
have occurred in the process.

3. Implement the Lamport algorithm: Implement the Lamport algorithm in the Process class.
When a process sends a message to another process, it should include its current logical
clock value in the message. When the receiving process receives the message, it should
update its own logical clock value to the maximum of its current value and the value
received in the message. When an event occurs in the process, it should be assigned a
timestamp that is the current logical clock value of the process.

4. Test the Lamport algorithm: Create a main class that creates a set of processes in the
34
Distributed System (3170719) 220183107024
distributed system. Each process should send messages to other processes and generate
events. The main class should display the events in the order determined by the Lamport
algorithm.

Algorithm works as follows :


 Whenever an event occurs in a process, the process increments its logical clock by 1 and
assigns the new value as the timestamp of the event.

 When a message is sent from one process to another, the sender includes its current logical
clock value as the timestamp of the message.

 When a process receives a message, it sets its logical clock to the maximum of its current
value and the timestamp of the received message plus 1. This ensures that the logical clock
of the receiving process is always greater than the logical clock of the sending process.

 The logical clock values assigned to events by each process can be used to determine the
ordering of events in the system.

Program Code:

import java.util.ArrayList;
import java.util.List;

class Event {
int timestamp;
int processId;

public Event(int timestamp, int processId) {


this.timestamp = timestamp;
this.processId = processId;
}
}

class Process {
int logicalClock;
int processId;
List<Event>
eventQueue;

public Process(int processId) {


this.processId = processId;
this.logicalClock = 0;
this.eventQueue = new
ArrayList<>();
}

public void sendEvent(Process receiver) {


this.logicalClock++;
Event event = new Event(this.logicalClock, this.processId);
receiver.receiveEvent(event);
}

public void receiveEvent(Event event) {


this.logicalClock = Math.max(this.logicalClock, event.timestamp) + 1; 35
eventQueue.add(event);
Distributed System (3170719) 220183107024
}

public void printEvents() {


for (Event event : eventQueue) {
System.out.println("Process " + event.processId + " Event " + event.timestamp);
}
}
}

public class LamportAlgorithm {


public static void main(String[] args) {
int numProcesses = 3;

Process[] processes = new Process[numProcesses];


for (int i = 0; i < numProcesses; i++) {
processes[i] = new Process(i + 1);
}

processes[0].sendEvent(processes[1]);
processes[1].sendEvent(processes[2]);
processes[2].sendEvent(processes[0]);
processes[1].sendEvent(processes[0]);

for (int i = 0; i < numProcesses; i++)


{ System.out.println("Events for Process " + (i +
1)); processes[i].printEvents();
System.out.println();
}
}
}
Conclusion:

Exercise:

1. What is the Lamport algorithm?


Ans: The Lamport algorithm, specifically known as Lamport's logical clock, is a method for
ordering events in a distributed computing system. It was developed by computer scientist
Leslie Lamport in 1978.

In a distributed system, where multiple processes or nodes communicate with each other, it's
important to establish a consistent ordering of events. However, due to the lack of a global
clock that synchronizes all processes, this can be challenging.

Lamport's algorithm provides a partial ordering of events based on timestamps. Each process in
the system maintains its own logical clock, which is essentially a counter that is incremented
whenever an event occurs. These timestamps are used to determine the relative ordering of
events.
36
Distributed System (3170719) 220183107024

The key principle of Lamport's algorithm is that if event A happened before event B, then the
timestamp of event A will be less than the timestamp of event B. However, it's important to
note that events that are concurrent (i.e., they don't have a causal relationship) may have the
same timestamp.

This algorithm allows processes in a distributed system to establish a consistent, albeit partial,
ordering of events, which is crucial for tasks like distributed databases, file systems, and other
distributed applications.

It's worth noting that Lamport's logical clocks are an example of a causality-tracking
mechanism, and they are often used in conjunction with other algorithms for achieving a more
complete ordering of events in distributed systems.

2. How does the Lamport algorithm ensure that events are ordered based on their logical clock
values?
Ans: The Lamport algorithm ensures that events are ordered based on their logical clock values
through the following mechanisms:

Timestamp Assignment: Each process in a distributed system maintains its own logical clock.
This clock is essentially a counter that gets incremented whenever an event occurs. The logical
clock values are assigned based on the order of events in each process.

Timestamp Comparison: When a process sends a message to another process, it includes its
current logical clock value in the message. When the receiving process receives the message, it
updates its own logical clock value to be greater than the maximum of its current value and the
received value plus one. This step ensures that the receiving process's clock reflects a time after
the sending process's clock.

Causality Enforcement: If event A causally precedes event B, then Lamport's algorithm


guarantees that the timestamp of event A will be less than the timestamp of event B. This
means that if event A and event B are in a causal relationship (A happened before B), then
their timestamps will reflect this relationship.

However, it's important to note that the algorithm does not provide an absolute ordering of all
events in the system, only a partial ordering based on causality.

In summary, the Lamport algorithm uses logical clocks and timestamp comparisons to
establish a partial ordering of events in a distributed system. It ensures that events are ordered
based on their logical clock values, providing a way to track causality in a distributed
environment where there is no global clock.

3. How can the Lamport algorithm be implemented using Java programming language?
Ans: public class Process implements Runnable {
private int processId;
private LamportClock clock;

public Process(int processId, LamportClock clock) {


this.processId = processId;
this.clock = clock;
}

public void sendEvent() {


37
Distributed System (3170719) 220183107024
// Increment the logical clock when an event occurs
clock.increment();
System.out.println("Event occurred in Process " + processId + " at timestamp " +
clock.getTimestamp());
}

public void sendMessage(Process receiver) {


// Include the sender's timestamp when sending a
message int senderTimestamp = clock.getTimestamp();
receiver.receiveMessage(senderTimestamp);
}

public void receiveMessage(int senderTimestamp) {


// Update the logical clock based on the received
timestamp clock.updateTimestamp(senderTimestamp);
System.out.println("Message received by Process " + processId + " with updated
timestamp " + clock.getTimestamp());
}

@Override
public void run()
{ sendEvent();
sendMessage(otherProcess);
}

public static void main(String[] args)


{ LamportClock clock1 = new
LamportClock(); LamportClock clock2 =
new LamportClock();

Process process1 = new Process(1, clock1);


Process process2 = new Process(2, clock2);

process1.run(); // Simulate an event and sending a message


process2.run(); // Simulate receiving the message

// Output will show events and messages along with their


timestamps
}
}

4. How can the Lamport algorithm be tested in a distributed


system?
Ans: Testing the Lamport algorithm in a distributed system
involves setting up multiple
processes that simulate independent nodes or machines. These processes will communicate
with each other, perform events, and exchange messages, while using Lamport's logical clocks
to order events. Here's a step-by-step guide to testing the Lamport algorithm in a distributed
system:

Set Up Multiple Processes:

Create separate instances of the program, each representing a process or node in the distributed
system. These processes can be run on different machines or on the same machine with 38
different ports.
Establish Communication:
Distributed System (3170719) 220183107024
Implement a communication mechanism between the processes. This could be done using
sockets, message queues, or any other suitable method for inter-process communication.
Initialize Lamport Clocks:

Each process should have its own instance of Lamport's logical clock.
Simulate Events:

In each process, simulate events that occur locally. This involves incrementing the logical
clock whenever an event occurs.
Send and Receive Messages:

Implement message sending and receiving functionalities in each process. When a process
sends a message, it includes its current logical clock value.
Update Logical Clocks on Message Receipt:

When a process receives a message, it updates its logical clock based on the received
timestamp and the local clock value.
Verify Event Ordering:

Print out or log the events and messages along with their timestamps. Verify that the ordering
of events and messages is consistent with the Lamport algorithm.
Test for Concurrent Events:

Create scenarios where events are concurrent (i.e., they do not have a causal relationship).
Verify that their timestamps do not strictly order them.
Perform Multiple Runs:

Test the system with various event sequences and message exchanges to ensure that the
Lamport algorithm consistently produces the expected results.

Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. Distributed Computing and application by M L Liu, Pearson Education Inc.
3. "Distributed Systems: Principles and Paradigms" by Andrew S. Tanenbaum and Maarten van Steen

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementation implementation implementation implementation implementation
as asked as asked as asked as asked as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

39
Distributed System (3170719) 220183107024
Experiment No: 7

Implementation of Lamport's Vector Clock Algorithm for Distributed Systems

Competency and Practical Skills: Network Programming & Programming Skill

Relevant CO: CO2

Objectives: (a) Understand the concept of Lamport Vector clock.


(b) Implement Lamport Vector clock in Java.
(c ) Test the implementation of Lamport Vector clock.

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans)

Theory:
Lamport Vector clock is a logical clock used in distributed systems. It is an extension of the
Lamport Logical Clock algorithm. In a distributed system, different processes execute
independently and communicate with each other by exchanging messages. In order to keep track of
the order of events in a distributed system, each process maintains a vector clock.

A vector clock is a list of integer values, where each value represents the number of events
that have occurred in each process up until that point in time. Each process increments its own
value in the vector clock whenever an event occurs, and sends the updated vector clock along with
the message to the other processes. When a process receives a message, it updates its own vector
clock by taking the maximum value of each element in its own vector clock and the vector clock
received in the message.

The Lamport Vector clock algorithm ensures that if event A happened before event B, then
the vector clock of A is less than the vector clock of B.

Safety and Necessary Precautions:


- Handle all necessary compile-time exceptions.
- Ensure that the processes are communicating with each other properly.

Procedure:
 Create a Java project in Eclipse or NetBeans.
 Create a Process class that implements Runnable interface. The Process class should have
the following:
o A name for the process.
o A vector clock to keep track of events.
o A method to update the vector clock when an event occurs.
o A run() method that simulates the process.
o A method to send messages to other processes.
 In the main() method, create an array of Process objects.
 Start each process in the array by calling the start() method.
 In the run() method of each Process object, simulate the occurrence of events and update
the vector clock accordingly.
 When a process sends a message to another process, it should update its own vector clock
and send the updated vector clock along with the message.
 When a process receives a message, it should update its own vector clock by taking the
maximum value of each element in its own vector clock and the vector clock received in
the message.
 Test the implementation of the Lamport Vector clock algorithm by running the program
and
observing the vector clocks of each process. 40
Distributed System (3170719) 220183107024

Program Code:

import java.util.Arrays;

class Process implements Runnable {


private String name;
private int[] vectorClock;
private Thread thread;

public Process(String name, int numProcesses) {


this.name = name;
this.vectorClock = new int[numProcesses];
this.thread = new Thread(this);
Arrays.fill(vectorClock, 0);
}

public void start() {


thread.start();
}

public void run() {


try {
// Simulate events and message passing
for (int i = 0; i < 5; i++) {
Thread.sleep((int) (Math.random() * 1000));
event();
sendRandomMessage();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}

private void event() {


int processId = Integer.parseInt(name) - 1;
vectorClock[processId]++;
System.out.println(name + " event occurred. Vector Clock: " +
Arrays.toString(vectorClock));
}

private void sendRandomMessage() {


int numProcesses = vectorClock.length;
int receiver = (int) (Math.random() *
numProcesses); sendMessage(receiver);
}

private void sendMessage(int receiver)


{ int numProcesses =
vectorClock.length; int sender =
Integer.parseInt(name) - 1;

// Increment sender's vector clock


vectorClock[sender]++; 41
Distributed System (3170719) 220183107024

// Simulate message delivery time


try {
Thread.sleep((int)
(Math.random() * 500));
} catch (InterruptedException e) {
e.printStackTrace();
}

// Update receiver's vector clock


for (int i = 0; i < numProcesses; i++)
{
vectorClock[i] =
Math.max(vectorClock[i],
vectorClock[receiver]);
}

System.out.println(name + " sent a message to Process " + (receiver + 1) +


". Vector Clock: " + Arrays.toString(vectorClock));
}
}

public class VectorClockAlgorithm


{ public static void main(String[]
args) {
int numProcesses = 3;
Process[] processes = new
Process[numProcesses];

for (int i = 0; i < numProcesses; i++) {


processes[i] = new Process(Integer.toString(i + 1), numProcesses);
processes[i].start();
}
}
}

42
Distributed System (3170719) 220183107024

Exercise:
1. What is the purpose of Lamport Vector Clocks in distributed systems?
Ans: Lamport Vector Clocks are an extension of Lamport's logical clocks designed to address
the limitations of the original algorithm in scenarios where more information about causality is
needed. They serve the following purposes in distributed systems:

Capturing Causality Relationships:

Lamport Vector Clocks allow for a more precise representation of causality between events in
a distributed system. Unlike logical clocks, vector clocks can capture the partial ordering of
events in a more detailed manner.
Determining Causality of Events:

They provide a way to determine whether two events are causally related or concurrent. This is
crucial for tasks like consistency management in distributed databases or maintaining the order
of operations in distributed systems.
Detecting Concurrent Events:

Vector clocks can identify events that occur concurrently. If two vector clocks have no relation
(neither is less than the other), it means the events are concurrent.
Ensuring Consistent State in Replicated Systems:

In systems with replicated data across multiple nodes, Lamport Vector Clocks can be used to
track updates and resolve conflicts. This helps ensure that each replica is in sync and maintains
a consistent state.
Ordering Messages and Events:

They can be used to order messages in a distributed system accurately. This is especially
important in scenarios where messages need to be processed in a specific order to maintain
correctness.
Distributed Algorithms:

Many distributed algorithms, like distributed consensus protocols (e.g., Paxos, Raft), rely on
vector clocks to make decisions about the state of the system.
Detecting Anomalies or Inconsistencies:

By analyzing vector clocks, it's possible to identify anomalies or inconsistencies in the


behavior of distributed processes. For example, unexpected changes in vector clock values can
signal a problem in the system.
Conflict Resolution:

In scenarios where concurrent updates may occur (e.g., in distributed databases), vector clocks
can be used to resolve conflicts and ensure that updates are applied in a consistent manner.
Overall, Lamport Vector Clocks play a crucial role in achieving a more comprehensive
understanding of causality in distributed systems. They provide a powerful tool for managing
the ordering of events and messages in a way that can lead to more robust and reliable
distributed applications.

2. How do Lamport Vector Clocks differ from Lamport Logical Clocks?


Ans: Lamport Vector Clocks and Lamport Logical Clocks are both mechanisms for tracking
the ordering of events in a distributed system, but they differ in several key ways:

43
Distributed System (3170719) 220183107024
Representation:

Lamport Logical Clocks:


Use a single integer value per process to represent the logical time. Each process increments its
own logical clock whenever an event occurs.
Lamport Vector Clocks:
Use an array of integers (or vector) to represent the logical time. Each element of the vector
corresponds to a process, and each process maintains its own counter.
Granularity of Information:

Lamport Logical Clocks:


Provide partial ordering of events based on their timestamps. They only establish a "happened
before" relationship between events.
Lamport Vector Clocks:
Provide a more detailed view of causality. They can capture the partial ordering of events in a
more precise manner and can determine whether events are causally related or concurrent.
Causality Determination:

Lamport Logical Clocks:


Determine causality based on timestamp comparison. If event A has a lower timestamp than
event B, then A causally precedes B.
Lamport Vector Clocks:
Determine causality based on vector comparison. They consider the entire vector, taking into
account the timestamps of all processes involved in the events.
Concurrent Event Detection:

Lamport Logical Clocks:


Cannot explicitly identify concurrent events. Events with equal timestamps are treated as
concurrent, even if there is a causal relationship.
Lamport Vector Clocks:
Can explicitly identify concurrent events. If the vector clocks of two events have no direct
relationship (neither is less than the other), they are considered concurrent.
Conflict Resolution:

Lamport Logical Clocks:


Do not provide a mechanism for resolving conflicts in distributed systems.
Lamport Vector Clocks:
Can be used to resolve conflicts, especially in scenarios where concurrent updates may occur
(e.g., distributed databases).
Complexity and Storage:

Lamport Logical Clocks:


Are simpler to implement and require less storage as they only involve a single integer value
per process.
Lamport Vector Clocks:
Are more complex to implement due to the use of arrays, and they require more storage since
each process maintains an array of timestamps.
In summary, while Lamport Logical Clocks provide a basic means of establishing a partial
ordering of events, Lamport Vector Clocks offer a more detailed and nuanced view of causality,
making them useful in scenarios where a finer-grained understanding of event ordering is
required. They are particularly valuable in distributed systems that require precise tracking of
causality relationships.

44
Distributed System (3170719) 220183107024
3. Can two events have the same Lamport timestamp in a distributed system?
Ans: Yes, two events can have the same Lamport timestamp in a distributed system. This
occurs when the events are considered concurrent, meaning there is no direct causal
relationship between them. In Lamport's logical clocks, events with the same timestamp are
treated as having occurred simultaneously or in an indeterminate order with respect to each
other.

Here's an example scenario to illustrate this:

Suppose we have two processes, A and B, in a distributed system. Both processes have their
own Lamport logical clocks:

Process A:

Event X: Timestamp = 10
Event Y: Timestamp = 11
Process B:

Event Z: Timestamp = 10
In this scenario, events X and Z have the same timestamp (10) because there is no causal
relationship between them. The clocks of processes A and B are independent, and they do not
communicate or influence each other's timestamps directly. Therefore, events X and Z are
considered concurrent.

It's important to note that even though events may have the same Lamport timestamp, they can
still be causally related if there is a chain of causality through other events. Lamport's logical
clocks provide a partial ordering of events based on causality, but they may not capture all
possible causal relationships in a distributed system. Lamport Vector Clocks are a more
advanced tool that can capture additional causality information in such cases.

4. How do you update a Lamport Vector Clock when a process receives a message from
another process?
Ans: When a process receives a message from another process in a distributed system, it needs
to update its Lamport Vector Clock to reflect the new information about causality. Here are the
steps to update a Lamport Vector Clock:

Receiving a Message:

When a process receives a message, it extracts the sender's vector clock from the message.
Updating the Vector Clock:

For each element in the vector, the process takes the maximum value between its own
timestamp for that process and the timestamp received in the message from the sender. Then, it
increments its own timestamp for itself.
Example:

Let's say process P2 receives a message from process P1. Their vector clocks are as follows:

P1: [3, 1, 2]
P2: [2, 4, 5]
After receiving the message, P2 updates its vector clock as follows:

P2: [max(2,3)+1, max(4,1)+1, max(5,2)+1] = [4, 5, 6]


Here, P2 increments its own timestamp for itself (P2) and takes the maximum value between
its 45
Distributed System (3170719) 220183107024
own timestamp and the received timestamp for processes P1 and P3.

Processing the Message:

The process then processes the message using its updated vector clock.
Sending Messages with Updated Vector Clock:

If the process sends further messages, it includes its updated vector clock in the message to
ensure that causality is correctly tracked for subsequent events.
By following these steps, a process ensures that its Lamport Vector Clock accurately reflects
the causality of events in the distributed system, taking into account information from received
messages. This allows for a more precise ordering of events and a better understanding of
causality relationships in the system.
5. How can you detect causality violations using Lamport Vector Clocks?
Ans: Causality violations can occur in a distributed system when events are ordered incorrectly,
potentially leading to incorrect behavior or results. Lamport Vector Clocks can be used to
detect these violations. Here's how you can do it:

Check for Invalid Orderings:

To detect causality violations, compare the vector clocks associated with events to ensure they
are in accordance with the happened-before relationship. Specifically, check if the vector clock
of one event is less than or equal to the vector clock of another event.
Identify Causality Violations:

If you find a pair of events A and B where the vector clock of A is not less than or equal to the
vector clock of B, then this indicates a causality violation. This means that event B is being
considered to have happened before event A, which is not consistent with the actual causal
relationship.
Example:

Let's consider two events, A and B, with their associated vector clocks:

Event A: [1, 0, 3]
Event B: [2, 1, 2]
If [1, 0, 3] ≤ [2, 1, 2], then causality is preserved. However, if [1, 0, 3] > [2, 1, 2], it indicates a
causality violation.

Investigate the Cause:

Once a causality violation is detected, investigate the events, message exchanges, and
processing logic to understand why the ordering is incorrect. This could be due to issues in
message delivery, incorrect vector clock updates, or other factors.
Debug and Correct the Code:

Review the code and logic related to event handling, message passing, and vector clock
updates. Identify and fix any bugs or logic errors that may be causing the causality violation.
Retest and Validate:

After making corrections, retest the system to ensure that causality is correctly maintained. Use
test cases that cover various scenarios to validate that the issue has been resolved.
By using Lamport Vector Clocks to compare the vector clocks associated with events, you can
systematically detect and address causality violations in a distributed system. This helps ensure
46
Distributed System (3170719) 220183107024
that events are correctly ordered according to their causal relationships.

6. Can Lamport Vector Clocks handle clock drifts between different processes?
Ans: Lamport Vector Clocks are not designed to handle clock drifts between different
processes. They assume that clocks across processes are synchronized, and any significant
clock drift can lead to inaccuracies in tracking causality.

Clock drift refers to the discrepancy in timekeeping between different clocks in a system. In a
distributed system, processes may have their own local clocks that may not be perfectly
synchronized. Over time, these clocks may drift apart due to factors such as hardware
variations, temperature changes, or clock inaccuracies.

If significant clock drift occurs, it can lead to incorrect ordering of events and potentially cause
causality violations when using Lamport Vector Clocks. For example, events that are actually
causally related may be assigned incorrect timestamps.

To handle clock drifts in a distributed system, more advanced clock synchronization techniques
and algorithms may be used. For instance, protocols like the Network Time Protocol (NTP) or
the Precision Time Protocol (PTP) can be employed to ensure more accurate time
synchronization across processes.

Additionally, more sophisticated logical clocks, like Hybrid Logical Clocks (HLC) or Google's
TrueTime, are designed to handle clock drifts and provide a more accurate representation of
time in distributed systems. These clocks incorporate mechanisms to account for both physical
time and logical ordering of events, allowing for better handling of scenarios involving clock
drift.

Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Distributed Systems: Principles and Paradigms" by Andrew S. Tanenbaum and Maarten
van Steen.
3. Distributed Computing and application by M L Liu, Pearson Education Inc.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

47
Distributed System (3170719) 220183107024
Experiment No: 8

To implement the functioning of Bully Algorithm

Competency and Practical Skills: Distributed Systems & Algorithm Design

Relevant CO: CO2

Objectives: (a) Implement the Bully Algorithm for a distributed system.


(b) Understand how the algorithm handles node failures and elections.
(c) Analyze the complexity and efficiency of the algorithm.

Equipment/Tools Required: Personal computer, IDE (Eclipse or NetBeans).

Theory:
The Bully Algorithm is a leader election algorithm that is used in distributed systems. It is a
way to elect a leader node among a group of nodes, with the assumption that the leader node will
be responsible for coordinating and managing the system.

The Bully Algorithm is a fault-tolerant algorithm that is designed to handle node failures.
When a node fails, the other nodes will detect the failure and start a new election process to elect a
new leader. The Bully Algorithm is designed to elect a leader with the highest priority among all
the nodes in the system.

Safety and Necessary Precautions:

Handle all necessary compile time Exception.

Procedure:

1. Create a Java class for the Node object that represents a node in the distributed system. The class
should have fields for the node ID and the priority of the node.

2. Implement a method for sending an election message to all the other nodes in the system.

3. Implement a method for receiving and processing messages from other nodes.

4. Implement a method for electing a new leader.

5. Implement a method for handling node failures.

6. Create a main class for the distributed system that creates and initializes the nodes, and starts the
election process.

7. Test the system by simulating node failures and observing how the algorithm handles them.

Algorithm:
 Each process in the network has a unique ID number.
 If a process P detects that the coordinator has failed, it sends an ELECTION message to all
processes with higher ID numbers.
 If a process Q receives an ELECTION message from P, it sends an OK message to P, indicating
that it is still alive.
48
Distributed System (3170719) 220183107024
 If a process Q does not receive a message from a higher-ID process within a certain time period,
it assumes that the higher-ID process has failed and initiates an election process.
 When a process R receives an OK message from all higher-ID processes, it becomes the new
coordinator and sends a COORDINATOR message to all other processes to inform them of the
new leader.

Program Code:
import java.util.ArrayList;
import java.util.List;

public class
BullyAlgorithm {
public static void main(String[] args)
{ List<Node> nodes = new
ArrayList<>();

nodes.add(new Node(1, 3, nodes));


nodes.add(new Node(2, 1, nodes));
nodes.add(new Node(3, 2,
nodes)); nodes.add(new Node(4,
5, nodes)); nodes.add(new
Node(5, 4, nodes));

nodes.get(3).setCoordinator(true);

for (Node node : nodes) {


if (node.isCoordinator()) {
System.out.println("Node " + node.getNodeId() + " is the current coordinator.");
node.sendElectionMessage();
break;
}
}
}
}

Conclusion:

Exercise :

1. What is the purpose of the Bully Algorithm?


Ans: The Bully Algorithm is a distributed algorithm used to elect a coordinator or leader in a
network of processes. Its primary purpose is to ensure that in the event of a failure or when a
new process joins the network, a single process is designated as the coordinator to manage
the distributed system effectively.

Here are the key purposes of the Bully Algorithm:

Leader Election:

49
Distributed System (3170719) 220183107024
The primary purpose of the Bully Algorithm is to elect a leader or coordinator among a group
of processes. This leader is responsible for making decisions and coordinating the activities
of the processes in the system.
Fault Tolerance:

The algorithm is designed to handle failures in a distributed system. If the current leader fails
or becomes unresponsive, the Bully Algorithm ensures that a new leader is elected to take
over the coordinator role.
Scalability:

The algorithm allows for scalability in distributed systems. As new processes join the network
or existing ones leave, the Bully Algorithm can re-elect a leader to maintain the coordination
and organization of the system.
Avoidance of Conflicts:

By designating a single coordinator, the Bully Algorithm helps prevent conflicts or race
conditions that may occur if multiple processes attempt to perform the same task
simultaneously.
Synchronization:

Having a designated leader allows for synchronized execution of tasks in the distributed
system. The leader can ensure that processes carry out their tasks in a coordinated manner.
Resource Allocation:

The coordinator, elected by the Bully Algorithm, is often responsible for managing shared
resources, allocating tasks, and ensuring that processes have access to the necessary resources.
Reduced Communication Overhead:

By designating a leader, the system can reduce the need for processes to communicate with
every other process in the network when making decisions. Instead, they can communicate
directly with the leader.
Decentralized Decision-Making:

The Bully Algorithm enables a decentralized system to autonomously elect a leader without
relying on a central authority or external intervention.
Overall, the Bully Algorithm plays a critical role in maintaining the stability and functionality
of distributed systems by ensuring that a single, reliable process is designated as the
coordinator to oversee the system's operations

2. How does the Bully Algorithm handle node failures?


Ans: The Bully Algorithm is designed to handle node failures in a distributed system by
initiating a leader election process when a higher-ranked node (a "bully") detects that the
current leader has failed or become unresponsive. Here's how the Bully Algorithm handles
node failures:

Detection of Node Failure:

When a node detects that the current leader has failed or is unresponsive, it initiates a leader
election process.
Election Message:

The node that detects the leader's failure sends an election message to all nodes with higher
ranks than itself.
50
Distributed System (3170719) 220183107024
Election Process:

Each higher-ranked node that receives the election message responds by either:
Acknowledging the election request and announcing its own candidacy.
Ignoring the request if it is not interested in becoming the leader.
Higher-Ranked Node Takes Over:

If no higher-ranked node responds, the initiating node declares itself as the new leader and
takes over the coordinator role.
Coordinator Propagation:

If a higher-ranked node responds and announces its candidacy, it then initiates its own
election process by sending election messages to nodes with even higher ranks. This process
continues until a node with the highest rank is identified.
Highest-Ranked Node Becomes Leader:

The highest-ranked node that successfully completes the election process becomes the new
leader and takes over the coordinator role.
Recovery and Resumption of Normal Operations:

Once a new leader is elected, normal operations in the distributed system can resume under
the coordination of the newly elected leader.
It's important to note that the Bully Algorithm assumes that nodes have unique ranks, and
higher-ranked nodes are considered more "powerful" or capable of taking on the coordinator
role. Additionally, the algorithm assumes that nodes are aware of each other's status and can
communicate reliably.

The Bully Algorithm provides fault tolerance by ensuring that a new leader is elected in the
event of a failure, helping to maintain the stability and functionality of the distributed system.
3. What happens when a node receives an election message from a node with a higher
priority?
Ans: When a node receives an election message from a node with a higher priority (rank) in
the Bully Algorithm, it must respond according to the protocol to ensure a proper leader
election process. Here are the steps a node takes when it receives an election message from a
higher-priority node:

Acknowledgment of Election:

The receiving node acknowledges the election message, indicating that it recognizes the
higher-priority node's candidacy for the leader position.
Announcement of Candidacy:

After acknowledging the election message, the receiving node announces its own candidacy
for the leader position. This means that it is willing to take on the role of leader if it is elected.
Initiation of Its Own Election Process:

The receiving node, now a candidate for the leader position, initiates its own election process
by sending election messages to nodes with even higher ranks than itself. This allows the
process to continue until a node with the highest rank is identified.
Propagation of the Election Process:

If the receiving node is the highest-ranked node that responded, it may become the new
leader. However, if it receives acknowledgment from an even higher-ranked node, it
acknowledges
51
Distributed System (3170719) 220183107024
that node's candidacy and initiates its own election process.
Highest-Ranked Node Becomes Leader:

The highest-ranked node that successfully completes the election process becomes the new
leader and takes over the coordinator role.
By following these steps, the receiving node ensures that the election process continues until
the highest-ranked node is identified and elected as the new leader. This allows for a reliable
leader election process in the event of a failure or unresponsiveness of the current leader.

Suggested Reference(s):
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest
Wiley Publication
2. "Distributed Systems: Principles and Paradigms" by Andrew S. Tanenbaum and
Maarten van Steen.

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

52
Distributed System (3170719) 220183107024
Experiment No: 09

Implement client server application using CORBA

Competency and Practical Skills: Network Programming & Programming Skill

Relevant CO: CO5

Objectives:

a) To learn about Common Object Request Broker Architecture (CORBA)


b) To implement a simple client-server application using CORBA
c) To understand the concept of interfaces in CORBA

Equipment/Tools Required: Personal Computer, JDK, IDE (Eclipse or NetBeans),


CORBA framework

Theory:

Common Object Request Broker Architecture (CORBA) is a standard for building


distributed systems. It allows objects written in different programming languages and running on
different platforms to communicate with each other. CORBA uses an Object Request Broker
(ORB) to manage communication between the objects. The ORB acts as an intermediary between
the client and server objects and provides services such as object lookup, object instantiation, and
parameter marshaling.

To use CORBA, you need to define an interface for your objects using the Interface
Definition Language (IDL). The IDL defines the methods and attributes that the objects will
expose to clients. The IDL compiler generates stub and skeleton code for the client and server
objects respectively. The stub and skeleton code provide the necessary marshaling and
unmarshaling of method arguments and results between the client and server.

The steps involved in implementing a simple client-server application using CORBA are:
 Define the IDL interface
 Compile the IDL interface using the IDL compiler
 Implement the server object
 Start the ORB
 Register the server object with the ORB
 Implement the client object
 Compile the client object
 Run the client object

Safety and necessary Precautions:


 Make sure that all the software required to run CORBA is installed and properly
configured.
 Handle all necessary compile time Exception

Procedure:
 Define the IDL interface: Define the interface for your objects using the Interface
Definition Language (IDL). The interface should include the methods and attributes
that the server object will expose to clients.

53
Distributed System (3170719) 220183107024
 Compile the IDL interface using the IDL compiler: Use the IDL compiler to
generate stub and skeleton code for the client and server objects respectively.
 Implement the server object: Implement the server object in Java using the skeleton
code generated by the IDL compiler. The server object should implement the
methods defined in the IDL interface.
 Start the ORB: Start the ORB by running the orb.run command.
 Register the server object with the ORB: Register the server object with the ORB
using the Naming Service.
 Implement the client object: Implement the client object in Java using the stub code
generated by the IDL compiler. The client object should invoke the methods
defined in the IDL interface.
 Compile the client object: Use the Java compiler to compile the client object.
 Run the client object: Run the client object and observe the results.

Program Code:

Server:
from omniORB import CORBA, PortableServer
import Example, Example POA

class StringManipulator_i (Example POA.StringManipulator):


def toUpperCase(self, input_str):
return input_str.upper()

orb = CORBA.ORB_init(["-ORBInitRef", "NameService=corbaname::localhost:2809"],


CORBA.ORB_ID)
poa = orb.resolve_initial_references("RootPOA")

ei = Example.StringManipulator
im = StringManipulator_i()
eo = im._this()

poaManager = poa._get_the_POAManager()
poaManager.activate()

ns = orb.resolve_initial_references("NameService")
nc = ns._narrow(CORBA.NamingContext)

if nc is None:
print("This is not a valid NamingContext")
sys.exit(1)

name = [CORBA.NameComponent("Example", "")]


nc.rebind(name, eo)

orb.run()

54
Distributed System (3170719) 220183107024
Client:

from omniORB import CORBA


orb = CORBA.ORB_init(["-ORBInitRef", "NameService=corbaname::localhost:2809"],
CORBA.ORB_ID)
ns = orb.resolve_initial_references("NameService")
nc = ns._narrow(CORBA.NamingContext)
name = [CORBA.NameComponent("Example", "")]
obj = nc.resolve(name)
eo = obj._narrow(Example.StringManipulator)
if eo is None:
print("Object reference is not an Example::StringManipulator")
sys.exit(1)
result = eo.toUpperCase("hello, world!")
print(result)

Conclusion:

In this practical, we implemented a basic CORBA (Common Object Request Broker Architecture)
application using Python. The application consists of a client and a server, communicating through
CORBA's middleware.

The server provides a simple interface StringManipulator with a single method toUpperCase,
which takes a string as input, converts it to uppercase, and returns the result.

The client establishes a connection to the server using CORBA's naming service. It then calls the
toUpperCase method on the server, passing a string. The server processes the request and sends
back the uppercase version of the string to the client.

This practical demonstrates the power of CORBA in enabling communication between distributed
objects in a platform-independent manner. CORBA allows objects written in different
programming languages to interact seamlessly, making it a valuable tool for building complex,
distributed systems.

Keep in mind that this example is simplified for educational purposes and lacks robust error
handling and security measures that would be necessary in a production environment. Additionally,
CORBA itself may not be the most modern or widely used technology for distributed systems, and
alternatives like RESTful APIs, gRPC, or more recent middleware technologies might be preferred
depending on the specific requirements of a project.

Suggested Reference(s):
1. "CORBA: Architecture and Programming with Java" by John Siegel and Thomas
Mowbray

55
Distributed System (3170719) 220183107024
Rubric wise marks obtained:
Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

56
Distributed System (3170719) 220183107024
Experiment 10

Implement a simple Web service in Java

Competency and Practical Skills: Web development, programming skills, and knowledge of
web services.

Relevant CO: CO5

Objectives:

a) Understand the basic concept of web services


b) Learn to create a web service using Java programming language
c) Learn to publish a web service on a web server
d) Learn to consume a web service using a client application

Equipment/Tools Required: Personal computer, Java Development Kit (JDK), Integrated


Development Environment (IDE) such as Eclipse or NetBeans, Apache Tomcat web server

Theory:
A web service is a software system designed to support interoperable machine-to-machine
interaction over a network. It has an interface described in a machine-processable format,
specifically WSDL (Web Service Description Language). Other systems interact with the web
service in a manner prescribed by its description using SOAP messages, typically conveyed using
HTTP with an XML serialization in conjunction with other web-related standards.

A web service comprises three parts:

Service provider: The application that provides the web service.


Service requester: The application that consumes the web service.
Registry: The application that contains the details of the web service provider, which can be
looked up by the service requester.

Apache Axis is one of the popular implementations of web services that is built on top of the
Apache SOAP project. It is an open-source, XML-based web service framework that provides a
means to generate WSDL and create client applications in various programming languages,
including Java.

Safety and necessary Precautions:


 Make sure to use secure communication protocols such as HTTPS to ensure the
confidentiality of data transmitted over the network.
 Make sure to validate user inputs and implement proper error handling mechanisms to
prevent attacks such as SQL injection.

Procedure:
 Create a Java project in Eclipse or NetBeans.
 Define the web service interface using the JAX-WS (Java API for XML Web Services)
annotations. This interface should declare the methods that will be exposed as web
service operations. Annotate the interface with @WebService and @WebMethod
annotations.
 Implement the web service interface in a Java class. Annotate the class with
@WebService and @WebServiceProvider annotations. Implement the methods
declared in the interface. 57
Distributed System (3170719) 220183107024

 Create a web application project in Eclipse or NetBeans. Add the Java class created in
step 3 to the project.
 Create a web service deployment descriptor (web.xml) file. This file should specify the
location of the web service implementation class and the URL mapping for the web
service endpoint.
 Deploy the web service to a web server such as Apache Tomcat. Publish the web
service by deploying the web application project created in step 4.
 Create a client application that will consume the web service. The client application can
be created in any programming language that supports SOAP messages. For this lab,
create a Java client application using the JAX-WS API.
 Generate the client artifacts using the wsimport tool provided by the JDK. This tool
generates Java classes that correspond to the WSDL of the web service.
 Use the generated Java classes to invoke the web service operations in the client
application.
 Run the client application and observe the results of invoking the web service
operations.

Program Code:

Java Class for the Web Service:


import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public class
SimpleWebService {

@WebMethod
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
Web Service Endpoint Interface (SEI):
import javax.jws.WebMethod;
import javax.jws.WebService;

@WebService
public interface
SimpleWebServiceInterface {

@WebMethod
String sayHello(String name);
}
Conclusion:
 Web services provide a means for different applications to interact with each other
over a network.
 Apache Axis is a popular implementation of web services that provides a means to
generate WSDL and create client applications in various programming languages.
 Web services can be published on a web server and consumed by client applications in
a secure and efficient manner.
58
Distributed System (3170719) 220183107024
Suggested References:
1. Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric Buest Wiley
Publication
2. "Java Web Services: Up and Running" by Martin Kalin

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

59
Distributed System (3170719) 220183107024

Experiment 11

Creation of BPEL and composite module

Competency: Web Services and SOA


Relevant CO : CO5
Objective: To create a BPEL process and
composite application using Oracle JDeveloper.

Tools Required: Oracle JDeveloper, Oracle


WebLogic Server

Theory:
A Business Process Execution Language (BPEL) process is an executable process that
describesthe behavior of a business process based on a set of activities, including receiving and
sending messages, invoking services, and manipulating data.

A composite application is an application that consists of multiple services and components


that are orchestrated to achieve a specific business goal. It is usually built using a Service
Oriented Architecture (SOA) approach, where each component provides a specific service that
can be accessed by other components.

In this lab, we will use Oracle JDeveloper to create a BPEL process and a composite
application that integrates multiple services.

Procedure:

Open Oracle JDeveloper and create a new application by selecting File > New > Application
from the menu.
 Select the "SOA Application" template and click "OK".
 In the "Create SOA Application" wizard, enter the application name and click "Next".
 In the "Select Template" page, select "Composite with BPEL" and click "Next".
 Enter the composite name and click "Finish".
 In the "composite.xml" file, drag and drop a "BPEL Process" component from the
Component Palette onto the design canvas.
 Double-click the "BPEL Process" component to open the "BPEL Process Editor".
 In the "BPEL Process Editor", add the required activities to define the business process,
such as "Receive", "Invoke", "Assign", and "Reply".
 Save the BPEL process by selecting File > Save from the menu.
 In the "composite.xml" file, drag and drop the required components from the
Component Palette onto the design canvas to create the composite application.
 Use the "Service Component Architecture" (SCA) editor to wire the components
together by creating "references" and "bindings".
 Save the composite application by selecting File > Save from the menu.
60
Distributed System (3170719) 220183107024
 Deploy the composite application to the Oracle WebLogic Server by right-clicking the
"composite.xml" file and selecting "Deploy".
 Test the composite application by accessing the services provided by the components.

Observations:

During the BPEL process creation, we observed that it is possible to add different activities to
the process to define the business logic.

In the composite application, we observed that the components can be easily wired together
using the SCA editor.

During deployment, we observed that the composite application is deployed as a single unit to
the Oracle WebLogic Server.

Conclusion:

Creating a BPEL process and composite module in Oracle SOA Suite is a powerful way to
model, orchestrate, and manage business processes. It provides a structured approach to
integrating various services and applications, allowing organizations to automate complex
workflows and improve operational efficiency.

Remember that this practical is a high-level overview, and actual implementation may involve
more detailed steps, including configuring service endpoints, defining data transformations,
implementing security measures, and conducting thorough testing in a controlled
environment. Additionally, documentation and version control are crucial aspects of real-
world development to ensure maintainability and scalability of your SOA projects.

Suggested Reference(s):
1. "Service-Oriented Architecture: Concepts, Technology, and Design" by Thomas Erl

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

61
Distributed System (3170719) 220183107024

Experiment 12

Study of open source Key Management tool

Competency and Practical Skills: Network Security and Cryptography.

Relevant CO: CO4

Objectives: (a) To understand the concept of


key management and its importance in cryptography
(b) To study various open source key management tools and
their features
(c) To evaluate and compare the performance of these tools

Equipment/Tools Required: Personal Computer, Internet Connection, Open Source Key


Management Tools (e.g., GnuPG, OpenSSL, Keyczar), Performance Evaluation Tools (e.g.,
Apache JMeter)

Theory:

Key management is an essential component of cryptography that involves generating,


storing, distributing, and revoking cryptographic keys. It ensures the secure and efficient
management of keys used in various cryptographic operations, such as encryption, decryption,
authentication, and digital signature. A key management system must provide robust key
generation and distribution mechanisms, secure storage, key backup and recovery options, and
support for various cryptographic algorithms and protocols.
Open source key management tools provide an affordable and customizable solution for
managing cryptographic keys. These tools offer a range of features, such as key pair generation,
key exchange, key storage and retrieval, key revocation, and certificate management. They
support various
cryptographic algorithms and protocols, including RSA, DSA, AES, SHA, and SSL/TLS.
In this experiment, we will study and evaluate some popular open source key management
tools, including GnuPG, OpenSSL, and Keyczar. We will analyze their features, strengths, and
weaknesses, and compare their performance using suitable evaluation metrics.

Conclusion:

The study of open-source Key Management tools demonstrates their vital role in securing
digital communications, transactions, and sensitive data. Selecting the right tool depends on
various factors, including the organization's size, compliance requirements, technology stack, and
specific security needs. Thorough evaluation, testing, and ongoing community support are
essential for successful implementation and maintenance of these tools. It's recommended that
organizations consider consulting with security experts or leveraging community forums to ensure
the chosen tool aligns with their unique requirements.

62
Distributed System (3170719) 220183107024

Suggested References:
1. OpenSSL - https://www.openssl.org/
2. GnuPG - https://gnupg.org/
3. Bouncy Castle - https://www.bouncycastle.org/
4. Keyczar - https://github.com/google/keyczar
5. Vault - https://www.vaultproject.io/
6. HashiCorp - https://www.hashicorp.com/
7. Apache Ranger - https://ranger.apache.org/

Rubric wise marks obtained:


Rubrics 1 2 3 4 5 Total
Marks Complete Complete Complete Complete Complete
implementatio implementatio implementatio implementatio implementatio
n as asked n as asked n as asked n as asked n as asked

Correct Result Correct Result Correct Result Correct Result

Conclusions Conclusions Conclusions

References References

Correct answer
to all
questions

63

You might also like