0% found this document useful (0 votes)
34 views12 pages

Java RPC and RMI Implementation Guide

The document discusses implementing remote procedure call (RPC) mechanisms in Java and Java RMI. It provides code samples to create a server and client for RPC using sockets in Java. It also provides code samples to create a server and client for Java RMI. The document then discusses simulating Lamport's logical clock algorithm in C programming language by creating physical and logical clocks. It provides a sample C program to do the same. Finally, the document asks to write a program in Java to simulate the Bully election algorithm.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views12 pages

Java RPC and RMI Implementation Guide

The document discusses implementing remote procedure call (RPC) mechanisms in Java and Java RMI. It provides code samples to create a server and client for RPC using sockets in Java. It also provides code samples to create a server and client for Java RMI. The document then discusses simulating Lamport's logical clock algorithm in C programming language by creating physical and logical clocks. It provides a sample C program to do the same. Finally, the document asks to write a program in Java to simulate the Bully election algorithm.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Implement RPC mechanism for accessing methods of remote systems in ‘JAVA’.

[Link]

import [Link].*;
import [Link].*;
class ser
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock = new ServerSocket(3000);
[Link]("Server ready");
Socket sock = [Link]( );
OutputStream ostream = [Link]();
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = [Link]();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String fun;
int a,b,c;
//while(true)
//{
fun = [Link]();
a = [Link]([Link]());
b = [Link]([Link]());
if(fun != null)
[Link]("Operation : "+fun);
[Link]("Parameter 1 : "+a);
[Link]("Parameter 2 : "+b);
if([Link]("add")==0)
{
c=a+b;
[Link]("Addition = "+c);
[Link]("Addition = "+c);
}
if([Link]("sub")==0)
{
c=a-b;
[Link]("Substraction = "+c);
[Link]("Substraction = "+c);
}
if([Link]("mul")==0)
{
c=a*b;
[Link]("Multiplication = "+c);
[Link]("Multiplication = "+c);
}
if([Link]("div")==0)

1
Prepared By: Abhishesh Dahal, Dinesh Gothe
{
c=a/b;
[Link]("Division = "+c);
[Link]("Division = "+c);
}
[Link]();
//}
}
}

[Link]

import [Link].*;
import [Link].*;
class cli
{
public static void main(String[] args) throws Exception
{
Socket sock = new Socket("localhost", 3000);
BufferedReader keyRead = new BufferedReader(new InputStreamReader([Link]));
OutputStream ostream = [Link]();
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = [Link]();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
[Link]("Client ready, type and press Enter key");
String receiveMessage, sendMessage1,sendMessage2, sendMessage3, temp;
//while(true)
//{
[Link]("\nEnter operation to perform(add,sub,mul,div)....");
temp = [Link]();
sendMessage1=[Link]();

[Link]("Enter first parameter :");


sendMessage2 = [Link]();

[Link]("Enter second parameter : ");


sendMessage3 = [Link]();

[Link](sendMessage1);
[Link](sendMessage2);
[Link](sendMessage3);

if((receiveMessage = [Link]()) != null)


[Link](receiveMessage);
//}
}
}

2
Prepared By: Abhishesh Dahal, Dinesh Gothe
2. Implement ‘JAVA RMI’ mechanism for accessing methods of remote systems.

[Link]

import [Link];
import [Link];
import [Link];
import [Link];

public class RmiServer extends UnicastRemoteObject implements RmiServerIntf {

public static final String MESSAGE = "Hello World";

public RmiServer() throws RemoteException {


super(0); // required to avoid the 'rmic' step, see below
}

public String getMessage() {


return MESSAGE;
}

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


[Link]("RMI server started");
try {
//special exception handler for registry creation
[Link](1099);
[Link]("java RMI registry created.");
} catch (RemoteException e) {
// do nothing, error means registry already exists
[Link]("java RMI registry already exists.");
}

//Instantiate RmiServer
RmiServer obj = new RmiServer();

// Bind this object instance to the name "RmiServer"


[Link]("//localhost/RmiServer", obj);
[Link]("PeerServer bound in registry");
}
}

3
Prepared By: Abhishesh Dahal, Dinesh Gothe
[Link]

import [Link];

public class RmiClient {

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


RmiServerIntf obj = (RmiServerIntf)[Link]("//localhost/RmiServer");
[Link]([Link]());
}
}

[Link]

import [Link];
import [Link];

public interface RmiServerIntf extends Remote {


public String getMessage() throws RemoteException;
}

4
Prepared By: Abhishesh Dahal, Dinesh Gothe
3. Write a program to simulate the functioning of Lamport’s logical clock in 'C’.

Lamport.c

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void main()
{
int i,j,k;
int x=0;
char a[10][10];
int n,num[10],b[10][10];
clrscr();

printf("Enter the no. of physical clocks: ");


scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("\nNo. of nodes for physical clock %d: ",i+1);
scanf("%d",&num[i]);

x=0;
for(j=0;j<num[i];j++)
{
printf("\nEnter the name of process: ");
scanf("%s",&a[i][j]);
b[i][j]=x + rand() % 10;
x=b[i][j]+1;
}
}

printf("\nPress a key for watching timestamp of physical clocks");


getch();

clrscr();
for(i=0;i<n;i++)
{
printf("Physical Clock %d: ",i+1);
for(j=0;j<num[i];j++)
{
printf("\nProcess: %c ",a[i][j]);
printf(" has P.T. : %d ",b[i][j]);
printf("\n");
}

5
Prepared By: Abhishesh Dahal, Dinesh Gothe
}
printf("Press a key for watching timestamp of logical clocks");
getch();

clrscr(); x=0; for(i=0;i<10;i++)


for(j=0;j<n;j++)
for(k=0;k<num[j];k++)
if(b[j][k]==i)
{
x = rand() % 10 + x;
printf("Logical Clock Timestamp for process %c",a[j][k]);
printf(":%d ",x);
printf("\n");
}
getch();
return;
}

Output

Enter the no. of physical clocks: 2


No. of nodes for physical clock 1: 2
Enter the name of process: a
Enter the name of process: b

No. of nodes for physical clock 2: 2


Enter the name of process: c
Enter the name of process: d

Press a key for watching timestamp of physical clocks

Physical Clock 1
Process a has P.T.: 6
Process b has P.T.: 7

Physical Clock 2
Process c has P.T.: 2
Process d has P.T.: 3

Press a key for watching timestamp of logical clocks

Logical Clock Timestamp for process a: 6


Logical Clock Timestamp for process b: 13
Logical Clock Timestamp for process c: 18
Logical Clock Timestamp for process d: 23

6
Prepared By: Abhishesh Dahal, Dinesh Gothe
4. Write a program to simulate the Election Algorithm (Bully Algorithm) in Java.

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

class Bully{
static int n;
static int pro[] = new int[100];
static int sta[] = new int[100];
static int co;

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


[Link]("Enter the number of process");
Scanner in = new Scanner([Link]);
n = [Link]();

int i,j,k,l,m;

for(i=0;i<n;i++)
{
[Link]("For process "+(i+1)+":");
[Link]("Status:");
sta[i]=[Link]();
[Link]("Priority");
pro[i] = [Link]();
}
[Link]("Which process will initiate election?");
int ele = [Link]();
elect(ele);
[Link]("Final coordinator is "+co);
}

static void elect(int ele){


ele = ele-1;
co = ele+1;
for(int i=0;i<n;i++)
{
if(pro[ele]<pro[i])
{
[Link]("Election message is sent from "+(ele+1)+" to "+(i+1));
if(sta[i]==1)
elect(i+1);
}
}
}
}

7
Prepared By: Abhishesh Dahal, Dinesh Gothe
Output

Enter the number of process:


7

For process 1:
Status: 1
Priority: 1
For process 2:
Status: 1
Priority: 2
For process 3:
Status: 1
Priority: 3
For process 4:
Status: 1
Priority: 4
For process 5:
Status: 1
Priority: 5
For process 6:
Status: 1
Priority: 6
For process 7:
Status: 0
Priority: 7

Which process will initiate election?


4

Election message is sent from 4 to 5

Election message is sent from 5 to 6

Election message is sent from 6 to 7

Election message is sent from 5 to 7

Election message is sent from 4 to 6

Election message is sent from 6 to 7

Election message is sent from 4 to 7

Final coordinator is 6

8
Prepared By: Abhishesh Dahal, Dinesh Gothe
5. Write a program to simulate the Distributed Mutual Exclusion in ‘C’.

MutualExclusion.c

#include<stdio.h>
#include<conio.h>
#include<dos.h>
#include<time.h>

void main()
{
int cs=0,pro=0;
double run=5;
char key='a';
time_t t1,t2;

clrscr();
printf("Press a key(except q) to enter a process into critical section.");
printf(" \nPress q at any time to exit.");

t1 = time(NULL) - 5;
while(key!='q')
{
while(!kbhit())
if(cs!=0)
{
t2 = time(NULL);
if(t2-t1 > run)
{
printf("Process%d ",pro-1);
printf(" exits critical section.\n");
cs=0;
}
}

key = getch();
if(key!='q')
{
if(cs!=0)
printf("Error: Another process is currently executing critical section
Please wait till its execution is over.\n");
else
{
printf("Process %d ",pro);
printf(" entered critical section\n");
cs=1;
pro++;

9
Prepared By: Abhishesh Dahal, Dinesh Gothe
t1 = time(NULL);
}
}
}
}

Output

Press a key (except q) to enter a process into critical section. Press q at any time to exit.

Process 0 entered critical section.

Error: Another process is currently executing critical section.


Please wait till its execution is over.

Process 0 exits critical section.

Process 1 entered critical section.

Process 1 exits critical section.

Process 2 entered critical section.

Error: Another process is currently executing critical section.


Please wait till its execution is over.

Process 2 exits critical section.

10
Prepared By: Abhishesh Dahal, Dinesh Gothe
6. Write a code in ‘C’ to implement sliding window protocol.

Sliding.c

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<dos.h>.

void main()
{
char sendFrame[4],receivedFrame[4],b;
int acknowledge[4];
int i,j,noFrame,sent,totalSent=0;

clrscr();

printf("Enter the number of frames: ");


scanf("%d", &noFrame);
for(i=0;i<noFrame;i++)
{
for(j=0;j<4;j++)
{
sendFrame[j]='0'+rand()%2;
}
printf("\n\nThe frame being sent is: %s",sendFrame);

retrysend:

for(j=0;j<4;j++)
{
if(rand()%500>80)
{
acknowledge[j]=1;
receivedFrame[j]=sendFrame[j];
}
else
{
acknowledge[j]=0;
receivedFrame[j]='x';
}
}
sent=1;
for(j=0;j<4;j++)
{
if(acknowledge[j]==0)
sent=0;

11
Prepared By: Abhishesh Dahal, Dinesh Gothe
delay(40);
printf("\nAcknowlegment for %d",j);
printf("th bit was: %d",acknowledge[j]);
}
receivedFrame[4]=NULL;
printf("\nThe frame received was:%s ",receivedFrame);
if(sent==1)
{
printf("\nThe frame sent was sent successfully ");
getch();
}
else
{
printf("\nThe frame was not sent!");
}
if(sent==0)
{
printf("\nDo you want to retry sending frame (y/n) ");
scanf("%c",&b);
if(b=='y' || b=='Y')
goto retrysend;
}
if(sent==1)
totalSent++;
}
printf("\n\nTotal Frames to be sent: %d",noFrame);
printf("\nTotal Frames sent successfully:%d ",totalSent);
getch();
}

12
Prepared By: Abhishesh Dahal, Dinesh Gothe

Common questions

Powered by AI

In the Java-based RPC system, the client (cli.java) sends user commands to the server (ser.java) through a socket connection. The server listens for connections, reads the command and parameters from the client, performs the corresponding arithmetic operation, and sends the result back to the client. The server code handles operations like addition, subtraction, multiplication, and division based on the client's request .

The C program for Distributed Mutual Exclusion manages access to the critical section by monitoring a flag (cs) that indicates if a process is currently in the critical section. If a process attempts to enter the critical section while the flag is set, it receives an error message and waits for the current process to leave. This ensures mutual exclusion by allowing only one process to enter the critical section at a time .

The Java code handles errors during the RMI registry creation by catching RemoteException. If the registry already exists, an exception is thrown, and the code outputs a message instead of halting execution. This error handling is crucial because it allows the server to proceed with operations even if the registry is pre-existing, thus maintaining service availability against unintended server stops due to redundant condition checks .

The remote interface RmiServerIntf defines the methods that can be invoked remotely by clients in the Java RMI architecture. By extending the Remote interface and specifying exceptions such as RemoteException, it establishes a contract for remote communication between the client and server. This interface facilitates client-server communication by providing a standardized set of method signatures for invoking operations on the server, ensuring type safety and consistency in remote method calls .

The RPC mechanism described allows a program to execute functions on a remote server as if they were local by using network communication. This differentiates from typical function calls as it involves marshalling parameters, sending them over the network, executing the function on the remote server, and receiving the result back. Advantages include abstracting the complexity of the network communication and allowing distributed systems to function more seamlessly .

The Sliding Window Protocol code in C demonstrates how frames of data are sent and acknowledged in a network. It simulates sending a sequence of frames and uses acknowledgments to verify successful delivery. If a frame is not acknowledged, it can be resent. This ensures reliable communication, efficient utilization of bandwidth, and management of network traffic by regulating the data flow with a limited window size .

A Java Remote Method Invocation (RMI) implementation primarily involves creating a remote interface, implementing the interface in a server, setting up a client to call the remote methods, and registering the remote object with a naming service. In the document, the RmiServer class implements the RmiServerIntf interface and binds the server object to the RMI registry using Naming.rebind. The RmiClient looks up this registry entry to obtain a reference to the remote object and calls its getMessage method .

The Lamport's logical clock simulation program operates by assigning timestamps to events in a distributed system using physical clocks, and then using those timestamps to update the logical clocks of the processes. This is significant in distributed systems for ensuring a causal order of events, which is crucial for coordinating activities and maintaining consistency across different nodes without a central clock .

The document's implementation of logical clocks uses timestamps not only based on physical clocks but also adjusted for event order, providing a logical sequence of events. Unlike physical clocks, which depend on actual time, logical clocks ensure events are causally related even if actual time differs. This approach benefits distributed systems by providing a consistent order of events for algorithmic correctness, reducing anomalies due to unsynchronized clock issues .

The Bully algorithm addresses the challenge of electing a coordinator in distributed systems, particularly in scenarios of a coordinator failure. It ensures that the process with the highest priority (id) ends up as the coordinator by sending election messages to higher-priority processes. If no response is received, it assumes the coordinator role. This prevents reliance on any single point of failure and isolates the leader election process to minimize disruption .

You might also like