Distributed System Lab
Distributed System Lab
Theory: Lamport's Logical Clock is a mechanism for ordering events in a distributed system. Each
process in the system maintains a logical clock that is incremented with each event, and it is used to
establish a partial ordering of events. The logical clock values are used to determine the order of events,
even if they occur on different processes.
Code:
#include <stdio.h>
typedef struct {
int id;
int logicalClock;
} Process;
process->logicalClock++;
int main() {
simulateEvent(&process1);
sendMessage(&process1, &process2);
simulateEvent(&process1);
simulateEvent(&process2);
sendMessage(&process2, &process1);
simulateEvent(&process2);
printLogicalClock(&process1);
printLogicalClock(&process2);
return 0;
Output:
Experiment No.:2
Objective: Simulate the Distributed Mutual Exclusion in ‘C’
Theory: Distributed Mutual Exclusion is a challenging problem in distributed systems where multiple
processes compete for access to a shared resource. One of the classical algorithms to achieve
distributed mutual exclusion is the Ricart-Agrawala algorithm. Below is a simple simulation of the
Ricart-Agrawala algorithm in C. Note that this is a basic example and might need modifications for a
real distributed environment.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <pthread.h>
#define N 5 // Number of processes
typedef struct {
bool requesting;
bool in_cs;
int timestamp;
} Process;
Process processes[N];
int clock = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
processes[process_id].requesting = true;
processes[process_id].timestamp = clock;
processes[process_id].requesting = false;
processes[process_id].in_cs = false;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&mutex);
}
void* process_function(void* arg) {
int process_id = *((int*)arg);
while (true) {
sleep(rand() % 5 + 1); // Simulate some processing time
request_critical_section(process_id);
// Critical Section
printf("Process %d enters the critical section.\n", process_id);
processes[process_id].in_cs = true;
sleep(rand() % 3 + 1); // Simulate some work in the critical section
processes[process_id].in_cs = false;
printf("Process %d exits the critical section.\n", process_id);
release_critical_section(process_id);
// Non-Critical Section
sleep(rand() % 5 + 1); // Simulate some processing time outside the critical section
}
return NULL;
}
int main() {
pthread_t threads[N];
int process_ids[N];
srand(time(NULL));
Client Side
Experiment No.:5
Objective: Implement ‘Java RMI’ mechanism for accessing methods of remote systems.
Theory: Java RMI (Remote Method Invocation) allows you to invoke methods on objects that reside in
another address space, often on a different machine. Below is a simple example of a Java RMI server
and client. In this example, we'll create a remote interface, a server implementation, and a client that
invokes methods on the remote server.
Code:
Create the remote interface (Calculator.java):
import java.rmi.Remote;
import java.rmi.RemoteException;
@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;
}
}
System.out.println("Server is ready.");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Output:
Experiment No.:6
Objective: Simulate Balanced Sliding Window Protocol in ‘C’.
Theory: The Balanced Sliding Window Protocol is a protocol used for reliable communication over a
network. It ensures that data sent by the sender is received correctly by the receiver, and it handles
issues such as packet loss and out-of-order delivery.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define WINDOW_SIZE 4
typedef struct {
int frame;
bool ack;
} Frame;
int main() {
int totalFrames = 12;
Frame frames[totalFrames];
printf("Simulation of Balanced Sliding Window Protocol\n\n");
printf("Initializing frames:\n");
for (int i = 0; i < totalFrames; i++) {
frames[i].frame = -1;
frames[i].ack = false;
}
return 0;
}
Output:
Experiment No.:7
Objective: Implement CORBA mechanism by using ‘C++’ program at one end and ‘Java program on
the other
Theory: Creating a CORBA-based client-server application involves several steps, including defining
an Interface Definition Language (IDL) file, generating stubs and skeletons, implementing the server in
C++, and creating the client in Java.
Code:
1. IDL File (example.idl):
module Example {
interface Calculator {
long add(in long a, in long b);
long subtract(in long a, in long b);
};
};
// Register the object reference with the naming service (if needed)
// ...
return 0;
}
// Obtain the object reference from the naming service (if needed)
// org.omg.CORBA.Object obj =
orb.string_to_object("IOR:PUT_YOUR_IOR_STRING_HERE");
// Obtain the object reference directly (if not using naming service)
org.omg.CORBA.Object obj = orb.string_to_object("corbaname::localhost:1050#Calculator");
// Display results
System.out.println("Result of addition: " + resultAdd);
System.out.println("Result of subtraction: " + resultSubtract);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Experiment No.:8
(Content Beyond Syllabus)
Objective: Develop a client server application which implements File Transfer protocol.
Theory: (FTP) is a standard network protocol used to transfer computer files from one host to
another host over a TCP-based network, such as the internet.
FTP is built on client-server architecture and used separate control and data connections between
the client and the server. FTP users may authenticate themselves using a clear-text sing-in-
protocol, normally in the form of a username and password, but can connect anonymously if the
server is configured to allow it. For secure transmission that protects the username and password
and encrypts the content, FTP is often secured with SSL/TLS. SSH File Transfer Protocol is
sometimes also used instead, but is technologically different.
Code:
FTP Client:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class One extends JFrame implements ActionListener
{
/* ctrl space */
setLayout(new GridLayout(2,3,10,10));
add(l);add(b);add(lmsg1);add(l1);add(b1);add(lmsg2);
b.addActionListener(this);
b1.addActionListener(this);
setVisible(true); setSize(600,500);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub try {
/* String s=e.getActionCommand();
if(s.equals("Upload"))*/
if (b.getModel().isArmed())
{
Socket s=new Socket("localhost",1010);
System.out.println("Client connected to server");
JFileChooser j=new JFileChooser();
int val;
val=j.showOpenDialog(One.this);
String filename=j.getSelectedFile().getName();
String path=j.getSelectedFile().getPath();
PrintStream out=new PrintStream(s.getOutputStream());
out.println("Upload");
out.println(filename);
FileInputStream fis=new FileInputStream(path); int n=fis.read();
while (n!=-1)
{
out.print((char)n);n=fis.read();
}
fis.close(); out.close();lmsg1.setText(filename+"is uploaded");
//s.close(); repaint();
}
if (b1.getModel().isArmed())
{
Socket s=new Socket("localhost",1010);
System.out.println("Client connected to server");
String remoteadd=s.getRemoteSocketAddress().toString();
System.out.println(remoteadd);
JFileChooser j1=new JFileChooser(remoteadd);
int val;
val=j1.showOpenDialog(One.this);
String filename=j1.getSelectedFile().getName();
String filepath=j1.getSelectedFile().getPath();
System.out.println("File name:"+filename);
PrintStream out=new PrintStream(s.getOutputStream());
out.println("Download");
out.println(filepath);
FileOutputStream fout=new FileOutputStream(filename);
DataInputStream fromserver=new DataInputStream(s.getInputStream());
int ch;
while ((ch=fromserver.read())!=-1)
{
fout.write((char) ch);
}
fout.close();
//s.close();
lmsg2.setText(filename+"is downlaoded");
repaint();
}
}
catch (Exception ee)
{
// TODO: handle exception System.out.println(ee);
}
}
}
public class FTPClient
{
public static void main(String[] args)
{
new One();
}
}
FTP Server:
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args)
{
try {
while (true)
{
ServerSocket ss=new ServerSocket(1010);
Socket sl=ss.accept();
System.out.println("Server scoket is created. ");
System.out.println(" test1");
DataInputStream fromserver=new DataInputStream(sl.getInputStream());
System.out.println(" test2");
String option=fromserver.readLine();
if (option.equalsIgnoreCase("upload"))
{
System.out.println("upload test");
String filefromclient=fromserver.readLine();
File clientfile=new File(filefromclient);
FileOutputStream fout=new FileOutputStream(clientfile);
int ch;
while ((ch=fromserver.read())!=-1)
{
fout.write((char)ch);
}
fout.close();
}
if (option.equalsIgnoreCase("download"))
{
System.out.println("download test");
String filefromclient=fromserver.readLine();
File clientfile=new File(filefromclient);
FileInputStream fis=new FileInputStream(clientfile);
PrintStream out=new PrintStream(sl.getOutputStream());
int n=fis.read();
while (n!=-1)
{
out.print((char)n); n=fis.read();
}
fis.close();
out.close();
} //while
}
}
catch (Exception e)
{
System.out.println(e);
// TODO: handle exception
}
}
}
Output:
Experiment No.:9
(Content Beyond Syllabus)
Objective: Implement a client server application which implements Name Server.
Theory: Name server is a client / server network communication protocol. Name server clients send
request to the server while name servers send response to the client. Client request contain a name
which is converted into in IP address known as a forward name server lookups while requests
containing an IP address which is converted into a name known as reverse name server lookups. Name
server implements a distributed database to store the name of all the hosts available on the internet. If a
client like a web browser sends a request containing a hostname, then a piece of software such as name
server resolver sends a request to the name server to obtain the IP address of a hostname. If name server
does not contain the IP address associated with a hostname then it forwards the request to another name
server. It IP address has arrived at the resolver, which in turn completes the request over the internet
protocol.
Code:
import java.net.*;
mport java.io.*;
import java.util.*;
public class DNS
{
public static void main(String[] args)
{
int n;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do
{
System.out.println("\n Menu: \n 1. DNS 2. Reverse DNS 3. Exit \n");
System.out.println("\n Enter your choice");
n = Integer.parseInt(System.console().readLine());
if(n==1)
{
try
{
System.out.println("\n Enter Host Name ");
String hname=in.readLine();
InetAddress address;
address = InetAddress.getByName(hname);
System.out.println("Host Name: " + address.getHostName());
System.out.println("IP: " + address.getHostAddress());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
if(n==2)
{
try
{
Output: