Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
299 views

Distributed System Practical File

The document contains code implementations for distributed computing concepts including: 1) Implementation of Lamport's logical clock algorithm for ordering events in a distributed system. 2) Implementation of a distributed mutual exclusion algorithm using message passing to coordinate access to a critical section across multiple nodes. 3) The distributed mutual exclusion code uses concepts like semaphores, message passing, and thread handling to simulate nodes requesting and granting access to a critical section in a distributed manner.

Uploaded by

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

Distributed System Practical File

The document contains code implementations for distributed computing concepts including: 1) Implementation of Lamport's logical clock algorithm for ordering events in a distributed system. 2) Implementation of a distributed mutual exclusion algorithm using message passing to coordinate access to a critical section across multiple nodes. 3) The distributed mutual exclusion code uses concepts like semaphores, message passing, and thread handling to simulate nodes requesting and granting access to a critical section in a distributed manner.

Uploaded by

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

List of Practicals

 Implementation of Lamport’s Logical Clock


 Implementation of Distributed Mutual Exclusion
 Implementation of Distributed Chat Server using TCP Sockets
 Implementation of ‘Java RMI’ Mechanism for Accessing
Methods of Remote Systems
 Implementation of CORBA (Common Object Request Broker
Architecture) Mechanism
 Implementation of RPC Mechanism for a File Transfer across a
network in ‘C’
Implementation of Lamport’s Logical Clock

#include<stdio.h>
#include<conio.h>
int max1(int a, int b) //to find the maximum timestamp between two events
{
if (a>b)
return a;
else
return b;
}

int main()
{
int i,j,k,p1[20],p2[20],e1,e2,dep[20][20];
printf("enter the events : ");
scanf("%d %d",&e1,&e2);
for(i=0;i<e1;i++)
p1[i]=i+1;
for(i=0;i<e2;i++)
p2[i]=i+1;
printf("enter the dependency matrix:\n");
printf("\t enter 1 if e1->e2 \n\t enter -1, if e2->e1 \n\t else enter 0 \n\n");
for(i=0;i<e2;i++)
printf("\te2%d",i+1);
for(i=0;i<e1;i++)
{
printf("\n e1%d \t",i+1);
for(j=0;j<e2;j++)
scanf("%d",&dep[i][j]);
}

for(i=0;i<e1;i++)
{
for(j=0;j<e2;j++)
{
if(dep[i][j]==1) //change the timestamp if dependency exist
{ p2[j]=max1(p2[j],p1[i]+1);
for(k=j;k<e2;k++)
p2[k+1]=p2[k]+1;
}
if(dep[i][j]==-1) //change the timestamp if dependency exist
{
p1[i]=max1(p1[i],p2[j]+1);
for(k=i;k<e1;k++)
p2[k+1]=p1[k]+1;
}

}
}
printf("P1 : "); //to print the outcome of Lamport Logical Clock
for(i=0;i<e1;i++)
{
printf("%d",p1[i]);
}
printf("\n P2 : ");
for(j=0;j<e2;j++)
printf("%d",p2[j]);

getch();
return 0 ;
}

Output: -
Implementation of Distributed Mutual Exclusion
import Utilities.*;
import Synchronization.*;

class Message { public int number, id;


public Message(int number, int id) { this.number = number; this.id = id;}
}

class Node extends MyObject implements Runnable {

private static final int MAIN = 0, REQUESTS = 1, REPLIES = 2;


private int whichOne = 0;

private int id = -1;


private int numNodes = -1;
private int napOutsideCS = 0; // both are in
private int napInsideCS = 0; // milliseconds
private MessagePassing[] requestChannel = null;
private MessagePassing[] replyChannel = null;
private MessagePassing requestsToMe = null;
private MessagePassing repliesToMe = null;
private int number = 0;
private int highNumber = 0;
private boolean requesting = false;
private int replyCount = 0;
private BinarySemaphore s = new BinarySemaphore(1);
private BinarySemaphore wakeUp = new BinarySemaphore(0);
private boolean[] deferred = null;

public Node(String name, int id, int numNodes,


int napOutsideCS, int napInsideCS,
MessagePassing[] requestChannel, MessagePassing replyChannel[],
MessagePassing requestsToMe, MessagePassing repliesToMe) {
super(name + " " + id);
this.id = id;
this.numNodes = numNodes;
this.napOutsideCS = napOutsideCS;
this.napInsideCS = napInsideCS;
this.requestChannel = requestChannel;
this.replyChannel = replyChannel;
this.requestsToMe = requestsToMe;
this.repliesToMe = repliesToMe;
deferred = new boolean[numNodes];
for (int i = 0; i < numNodes; i++) deferred[i] = false;
System.out.println(getName() + " is alive, napOutsideCS="
+ napOutsideCS + ", napInsideCS=" + napInsideCS);
new Thread(this).start();
}

public void run() { // start three different threads in the same object
int meDo = whichOne++;
if (meDo == MAIN) {
new Thread(this).start();
main();
} else if (meDo == REQUESTS) {
new Thread(this).start();
handleRequests();
} else if (meDo == REPLIES) {
handleReplies();
}
}

private void chooseNumber() {


P(s);
requesting = true;
number = highNumber + 1;
V(s);
}

private void sendRequest() {


replyCount = 0;
for (int j = 0; j < numNodes; j++) if (j != id)
send(requestChannel[j], new Message(number, id));
}

private void waitForReply() {


P(wakeUp);
}

private void replyToDeferredNodes() {


P(s);
requesting = false;
V(s);
for (int j = 0; j < numNodes; j++) {
if (deferred[j]) {
deferred[j] = false;
send(replyChannel[j], id);
}
}
}

private void outsideCS() {


int napping;
napping = ((int) random(napOutsideCS)) + 1;
System.out.println("age()=" + age() + ", " + getName()
+ " napping outside CS for " + napping + " ms");
nap(napping);
}

private void insideCS() {


int napping;
napping = ((int) random(napInsideCS)) + 1;
System.out.println("age()=" + age() + ", " + getName()
+ " napping inside CS for " + napping + " ms");
nap(napping);
}

private void main() {


while (true) {
outsideCS();
System.out.println("age()=" + age() + ", node " + id
+ " wants to enter its critical section");
chooseNumber(); // PRE-PROTOCOL
sendRequest(); // "
waitForReply(); // "
insideCS();
System.out.println("age()=" + age() + ", node " + id
+ " has now left its critical section");
replyToDeferredNodes(); // POST-PROTOCOL
}
}

private void handleRequests() {


while (true) {
Message m = (Message) receive(requestsToMe);
int receivedNumber = m.number;
int receivedID = m.id;
highNumber = Math.max(highNumber, receivedNumber);
P(s);
boolean decideToDefer = requesting && (number < receivedNumber
|| (number == receivedNumber && id < receivedID));
if (decideToDefer) deferred[receivedID] = true;
else send(replyChannel[receivedID], id);
V(s);
}
}

private void handleReplies() {


while (true) {
int receivedID = receiveInt(repliesToMe);
replyCount++;
if (replyCount == numNodes - 1) V(wakeUp);
}
}
}

class DistributedMutualExclusion extends MyObject {

public static void main(String[] args) {

// parse command line options, if any, to override defaults


GetOpt go = new GetOpt(args, "Un:R:");
String usage = "Usage: -n numNodes -R runTime"
+ " napOutsideCS[i] napInsideCS[i] i=0,1,...";
go.optErr = true;
int ch = -1;
int numNodes = 5;
int runTime = 60; // seconds
while ((ch = go.getopt()) != go.optEOF) {
if ((char)ch == 'U') {
System.out.println(usage); System.exit(0);
}
else if ((char)ch == 'n')
numNodes = go.processArg(go.optArgGet(), numNodes);
else if ((char)ch == 'R')
runTime = go.processArg(go.optArgGet(), runTime);
else {
System.err.println(usage); System.exit(1);
}
}
System.out.println("DistributedMutualExclusion: numNodes="
+ numNodes + ", runTime=" + runTime);

// process non-option command line arguments


int[] napOutsideCS = new int[numNodes];
int[] napInsideCS = new int[numNodes];
int argNum = go.optIndexGet();
for (int i = 0; i < numNodes; i++) {
napOutsideCS[i] = go.tryArg(argNum++, 8);
napInsideCS[i] = go.tryArg(argNum++, 2);
}
// create communication channels
MessagePassing[] requestChannel = null, replyChannel = null,
requestChannelS = null, requestChannelR = null,
replyChannelS = null, replyChannelR = null;
requestChannel = new MessagePassing[numNodes];
replyChannel = new MessagePassing[numNodes];
requestChannelS = new MessagePassing[numNodes];
replyChannelS = new MessagePassing[numNodes];
requestChannelR = new MessagePassing[numNodes];
replyChannelR = new MessagePassing[numNodes];
for (int i = 0; i < numNodes; i++) {
requestChannel[i] = new AsyncMessagePassing();
replyChannel[i] = new AsyncMessagePassing();
requestChannelS[i] = new MessagePassingSendOnly(requestChannel[i]);
replyChannelS[i] = new MessagePassingSendOnly(replyChannel[i]);
requestChannelR[i] = new MessagePassingReceiveOnly(requestChannel[i]);
replyChannelR[i] = new MessagePassingReceiveOnly(replyChannel[i]);
}

// create the Nodes (they start their own threads)


for (int i = 0; i < numNodes; i++)
new Node("Node", i, numNodes,
napOutsideCS[i]*1000, napInsideCS[i]*1000,
requestChannelS, replyChannelS,
requestChannelR[i], replyChannelR[i]);
System.out.println("All Nodes created");

// let the Nodes run for a while


nap(runTime*1000);
System.out.println("age()=" + age()
+ ", time to stop the threads and exit");
System.exit(0);
}
}

Output: -

DistributedMutualExclusion: numNodes=5, runTime=20


Node 0 is alive, napOutsideCS=8000, napInsideCS=2000
Node 1 is alive, napOutsideCS=8000, napInsideCS=2000
Node 2 is alive, napOutsideCS=8000, napInsideCS=2000
Node 3 is alive, napOutsideCS=8000, napInsideCS=2000
Node 4 is alive, napOutsideCS=8000, napInsideCS=2000
age()=170, Node 1 napping outside CS for 2719 ms
age()=170, Node 2 napping outside CS for 279 ms
All Nodes created
age()=170, Node 3 napping outside CS for 2355 ms
age()=220, Node 0 napping outside CS for 2393 ms
age()=220, Node 4 napping outside CS for 8 ms
age()=220, node 4 wants to enter its critical section
age()=330, Node 4 napping inside CS for 911 ms
age()=440, node 2 wants to enter its critical section
age()=1260, node 4 has now left its critical section
age()=1260, Node 4 napping outside CS for 4042 ms
age()=1260, Node 2 napping inside CS for 183 ms
age()=1480, node 2 has now left its critical section
age()=1480, Node 2 napping outside CS for 7335 ms
age()=2530, node 3 wants to enter its critical section
age()=2530, Node 3 napping inside CS for 741 ms
age()=2580, node 0 wants to enter its critical section
age()=2860, node 1 wants to enter its critical section
age()=3300, node 3 has now left its critical section
age()=3300, Node 3 napping outside CS for 6849 ms
age()=3300, Node 0 napping inside CS for 1710 ms
age()=5000, node 0 has now left its critical section
age()=5000, Node 0 napping outside CS for 5253 ms
age()=5000, Node 1 napping inside CS for 1694 ms
age()=5330, node 4 wants to enter its critical section
age()=6700, node 1 has now left its critical section
age()=6700, Node 1 napping outside CS for 3063 ms
age()=6700, Node 4 napping inside CS for 397 ms
age()=7140, node 4 has now left its critical section
age()=7140, Node 4 napping outside CS for 3687 ms
age()=8790, node 2 wants to enter its critical section
age()=8790, Node 2 napping inside CS for 102 ms
age()=8900, node 2 has now left its critical section
age()=8900, Node 2 napping outside CS for 1174 ms
age()=9780, node 1 wants to enter its critical section
age()=9780, Node 1 napping inside CS for 1617 ms
age()=10110, node 2 wants to enter its critical section
age()=10160, node 3 wants to enter its critical section
age()=10270, node 0 wants to enter its critical section
age()=10820, node 4 wants to enter its critical section
age()=11430, node 1 has now left its critical section
age()=11430, Node 1 napping outside CS for 5326 ms
age()=11430, Node 2 napping inside CS for 628 ms
age()=12090, node 2 has now left its critical section
age()=12090, Node 2 napping outside CS for 4970 ms
age()=12090, Node 3 napping inside CS for 545 ms
age()=12630, node 3 has now left its critical section
age()=12630, Node 3 napping outside CS for 7989 ms
age()=12630, Node 0 napping inside CS for 904 ms
age()=13510, node 0 has now left its critical section
age()=13510, Node 0 napping outside CS for 4162 ms
age()=13510, Node 4 napping inside CS for 1440 ms
age()=15000, node 4 has now left its critical section
age()=15000, Node 4 napping outside CS for 2578 ms
age()=16750, node 1 wants to enter its critical section
age()=16750, Node 1 napping inside CS for 123 ms
age()=16860, node 1 has now left its critical section
age()=16860, Node 1 napping outside CS for 3709 ms
age()=17030, node 2 wants to enter its critical section
age()=17030, Node 2 napping inside CS for 97 ms
age()=17140, node 2 has now left its critical section
age()=17140, Node 2 napping outside CS for 7901 ms
age()=17580, node 4 wants to enter its critical section
age()=17580, Node 4 napping inside CS for 1695 ms
age()=17690, node 0 wants to enter its critical section
age()=19280, node 4 has now left its critical section
age()=19280, Node 4 napping outside CS for 3751 ms
age()=19280, Node 0 napping inside CS for 869 ms
age()=20160, node 0 has now left its critical section
age()=20160, Node 0 napping outside CS for 6489 ms
age()=20160, time to stop the threads and exit
... end of example run(s) */
Implementation of a Distributed Chat Server using TCP Sockets

1.Server.java

import java.net.*;
import java.io.*;
public class server{
public static void main(String args[])throws IOException{
ServerSocket s1=null;
try{
s1=new ServerSocket(98);
}catch(Exception e){
System.out.println("Port not found");
e.printStackTrace();
}
Socket c=null;
try{
c=s1.accept();
System.out.println("Connection from"+c);
}catch(Exception e){
System.out.println("not accepted");
e.printStackTrace();
}
PrintWriter out=new PrintWriter(c.getOutputStream(),true);
BufferedReaderin=new BufferedReader(new InputStreamReader(c.getInputStream()));
String l;
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
System.out.println("I am ready type now");
while((l=sin.readLine())!=null){
out.println(l);
}
out.close();
sin.close();
c.close();
s1.close();
}
}
2.Client.java

import java.net.*;
import java.io.*;
public class client{
public static void main(String args[])throws IOException{
Socket s=null;
BufferedReader b=null;
try{
s=new Socket(InetAddress.getLocalHost(),98);
b=new BufferedReader(new InputStreamReader(s.getInputStream()));
}catch(Exception e){
System.out.println("I do not host");
e.printStackTrace();
}
String inp;
while((inp=b.readLine())!=null){
System.out.println(inp);
}
b.close();
s.close();
}
}

Running the application


Open two cmd prompt and follow these
1.java Server
2.java client

Output: -
D:\Sagar\RND\Java\NetWorking\ChatServer>java server
Connection fromSocket[addr=/127.0.0.1,port=1120,localport=98]
I am ready type now
Hello how r u? dude…
D:\Sagar\RND\Java\NetWorking\ChatServer>java client
Hello how r u? dude…
Implementation of ‘Java RMI’ Mechanism for Accessing Methods of
Remote Systems

1.CalculatorImpl.java
public class CalculatorImpl
extends
java.rmi.server.UnicastRemoteObject
implements Calculator {
public CalculatorImpl()
throws java.rmi.RemoteException {
super();
}
public long add(long a, long b)
throws java.rmi.RemoteException {
return a + b;
}
public long sub(long a, long b)
throws java.rmi.RemoteException {
return a - b;
}
public long mul(long a, long b)
throws java.rmi.RemoteException {
return a * b;
}
public long div(long a, long b)
throws java.rmi.RemoteException {
return a / b;
}
}

2.Calculator.java
public interface Calculator
extends java.rmi.Remote {
public long add(long a, long b)
throws java.rmi.RemoteException;
public long sub(long a, long b)
throws java.rmi.RemoteException;
public long mul(long a, long b)
throws java.rmi.RemoteException;
public long div(long a, long b)
throws java.rmi.RemoteException;
}
3.CalculatorServer.java

import java.rmi.Naming;
public class CalculatorServer {
public CalculatorServer() {
try {
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost:1099/CalculatorService", c);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public static void main(String args[]) {
new CalculatorServer();
}
}

4.CalculatorClient.java
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
public class CalculatorClient {
public static void main(String[] args) {
try {
Calculator c = (Calculator)
Naming.lookup("rmi://localhost/CalculatorService");
System.out.println( c.sub(4, 3) );
System.out.println( c.add(4, 5) );
System.out.println( c.mul(3, 6) );
System.out.println( c.div(9, 3) );
}
catch (MalformedURLException murle) {
System.out.println();
System.out.println("MalformedURLException");
System.out.println(murle);
}
catch (RemoteException re) {
System.out.println();
System.out.println("RemoteException");
System.out.println(re);
}
catch (NotBoundException nbe) {
System.out.println();
System.out.println(
"NotBoundException");
System.out.println(nbe);
}
catch ( java.lang.ArithmeticException ae) {
System.out.println();
System.out.println(
"java.lang.ArithmeticException");
System.out.println(ae);
}
}
}

Running the Application:


D:\Sagar\RND\Java\NetWorking\RMI>rmic CalculatorImpl
Now open three cmd prompts and follow these at each.
1. D:\Sagar\RND\Java\NetWorking\RMI>Rmiregistry
2. D:\Sagar\RND\Java\NetWorking\RMI>java CalculatorServer
3. D:\Sagar\RND\Java\NetWorking\RMI>java CalculatorClient

Output:
If all goes well you will see the following output:

1
9
18
3
Implementation of CORBA (Common Object Request Broker
Architecture) Mechanism

1.FileInterface.idl
interface FileInterface {
typedef sequence<octet> Data;
Data downloadFile(in string fileName);
};

Now, let's compile the FileInterface.idl and generate server-side skeletons. Using the
command:

D:\Sagar\RND\Java\CORBA> idlj -fserver FileInterface.idl

2.FileServant.java
import java.io.*;

public class FileServant extends _FileInterfaceImplBase {


public byte[] downloadFile(String fileName){
File file = new File(fileName);
byte buffer[] = new byte[(int)file.length()];
try {
BufferedInputStream input = new
BufferedInputStream(new FileInputStream(fileName));
input.read(buffer,0,buffer.length);
input.close();
} catch(Exception e) {
System.out.println("FileServant Error: "+e.getMessage());
e.printStackTrace();
}
return(buffer);
}
}

3.FileServer.java
import java.io.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextPackage.*;
import org.omg.CORBA.*;

public class FileServer {


public static void main(String args[]) {
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// create the servant and register it with the ORB
FileServant fileRef = new FileServant();
orb.connect(fileRef);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Bind the object reference in naming
NameComponent nc = new NameComponent("FileTransfer", " ");
NameComponent path[] = {nc};
ncRef.rebind(path, fileRef);
System.out.println("Server started....");
// Wait for invocations from clients
java.lang.Object sync = new java.lang.Object();
synchronized(sync){
sync.wait();
}
} catch(Exception e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace(System.out);
}
}
}

4.FileClient.java
import java.io.*;
import java.util.*;
import org.omg.CosNaming.*;
import org.omg.CORBA.*;

public class FileClient {


public static void main(String argv[]) {
try {
// create and initialize the ORB
ORB orb = ORB.init(argv, null);
// get the root naming context
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
NameComponent nc = new NameComponent("FileTransfer", " ");
// Resolve the object reference in naming
NameComponent path[] = {nc};
FileInterfaceOperations fileRef =
FileInterfaceHelper.narrow(ncRef.resolve(path));

if(argv.length < 1) {
System.out.println("Usage: java FileClient filename");
}

// save the file


File file = new File(argv[0]);
byte data[] = fileRef.downloadFile(argv[0]);
BufferedOutputStream output = new
BufferedOutputStream(new FileOutputStream(argv[0]));
output.write(data, 0, data.length);
output.flush();
output.close();
} catch(Exception e) {
System.out.println("FileClient Error: " + e.getMessage());
e.printStackTrace();
}
}
}

Running the application

1. D:\Sagar\RND\Java\CORBA>tnameserv
2. D:\Sagar\RND\Java\CORBA>java FileServer
3. D:\Sagar\RND\Java\CORBA>idlj -fclient FileInterface.idl
4. D:\Sagar\RND\Java\CORBA>java FileClient hello.txt

Output:
Implementation of RPC Mechanism for a File Transfer across a
network in ‘C’

/*
* rdate.c client program for remote date program
*/

#include <stdio.h>
#include <rpc/rpc.h> /* standard RPC include file */
#include "date.h" /* this file is generated by rpcgen */

main(int argc, char *argv[])


{
CLIENT *cl; /* RPC handle */
char *server;
long *lresult; /* return value from bin_date_1() */
char **sresult; /* return value from str_date_1() */
if (argc != 2) {
fprintf(stderr, "usage: %s hostname\n", argv[0]);
exit(1);
}
server = argv[1];

/*
* Create client handle
*/
if ((cl = clnt_create(server, DATE_PROG, DATE_VERS, "udp")) == NULL) {
/*
* can’t establish connection with server
*/
clnt_pcreateerror(server);
exit(2);
}

/*
* First call the remote procedure "bin_date".
*/

if ( (lresult = bin_date_1(NULL, cl)) == NULL) {


clnt_perror(cl, server);
exit(3);
}
printf("time on host %s = %ld\n",server, *lresult);

/*
* Now call the remote procedure str_date
*/
if ( (sresult = str_date_1(lresult, cl)) == NULL) {
clnt_perror(cl, server);
exit(4);
}
printf("time on host %s = %s", server, *sresult);
clnt_destroy(cl); /* done with the handle */
exit(0);
}

/*
* date.x Specification of the remote date and time server
*/

/*
* Define two procedures
* bin_date_1() returns the binary date and time (no arguments)
* str_date_1() takes a binary time and returns a string
*
*/

program DATE_PROG {
version DATE_VERS {
long BIN_DATE(void) = 1; /* procedure number = 1 */
string STR_DATE(long) = 2; /* procedure number = 2 */
} = 1; /* version number = 1 */
} = 0x31234567;

/*
* dateproc.c remote procedures; called by server stub
*/

#include <time.h>
#include <rpc/rpc.h> /* standard RPC include file */
#include "date.h" /* this file is generated by rpcgen */

/*
* Return the binary date and time
*/

long *bin_date_1_svc(void *arg, struct svc_req *s)


{
static long timeval; /* must be static */
timeval = time((long *) 0);
return(&timeval);
}
/*
* Convert a binary time and return a human readable string
*/

char **str_date_1_svc(long *bintime, struct svc_req *s)


{
static char *ptr; /* must be static */
ptr = ctime((const time_t *)bintime); /* convert to local time */
return(&ptr);
}

You might also like