0% found this document useful (0 votes)
3 views23 pages

All Codes

The document contains multiple Java source code implementations for distributed computing concepts, including RMI for addition and string reversal, MPI for scatter-gather operations, a socket-based time synchronization server-client model, token ring communication, and election algorithms like Bully. Each implementation demonstrates a different aspect of network communication or process coordination. The code is structured to showcase client-server interactions, data handling, and process management in a distributed environment.
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)
3 views23 pages

All Codes

The document contains multiple Java source code implementations for distributed computing concepts, including RMI for addition and string reversal, MPI for scatter-gather operations, a socket-based time synchronization server-client model, token ring communication, and election algorithms like Bully. Each implementation demonstrates a different aspect of network communication or process coordination. The code is structured to showcase client-server interactions, data handling, and process management in a distributed environment.
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

Source Code:

// [Link]
import [Link].*;
public interface AddServerIntf extends Remote
{
double add(double d1,double d2) throws RemoteException;
}

// [Link]
import [Link].*;
import [Link].*;
public class AddServerImpl extends UnicastRemoteObject
implements AddServerIntf
{
public AddServerImpl() throws RemoteException
{
}
public double add(double d1,double d2) throws RemoteException
{
return d1+d2;
}
}

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

public class AddServer {

public static void main(String args[]) {

try {

AddServerImpl obj = new AddServerImpl();

[Link]("AddServer", obj);

[Link]("Server Started...");

} catch(Exception e) {
[Link]("Exception: " + e);

}
}

// [Link]
import [Link].*;
public class AddClient
{
public static void main(String args[])
{
try
{
String addServerURL = "rmi://" + args[0] + "/AddServer";
AddServerIntf addServerIntf =
(AddServerIntf)[Link](addServerURL);
[Link]("The first number is: " + args[1]);
double d1 = [Link](args[1]).doubleValue();
[Link]("The second number is: " + args[2]);
double d2 = [Link](args[2]).doubleValue();
[Link]("The sum is: " +
[Link](d1,d2));
}

catch(Exception e)
{
[Link]("Exception: " + e);
}
}
}
OUTPUT:
Source Code:
// [Link]
import ReverseModule.*;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;
class ReverseServer

public static void main(String[] args)

try

// initialize the ORB


ORB orb = [Link](args, null);

// initialize the POA

POA rootPOA = [Link](

orb.resolve_initial_references("RootPOA"));

rootPOA.the_POAManager().activate();

// create servant object

ReverseImpl rvr = new ReverseImpl();


// get object reference from servant
[Link] ref =

rootPOA.servant_to_reference(rvr);

[Link]("Step1");

Reverse h_ref =

[Link](ref);

[Link]("Step2");

// get naming context


[Link] objRef =

orb.resolve_initial_references("NameService");

[Link]("Step3");

NamingContextExt ncRef =
[Link](objRef);

[Link]("Step4");

// bind object with name

String name = "Reverse";

NameComponent path[] = ncRef.to_name(name);

[Link](path, h_ref);

[Link]("Reverse Server reading and waiting...");


[Link]();

catch(Exception e)

[Link]();

}
}

//[Link]
import ReverseModule.*;

import [Link].*;

import [Link].*;

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

class ReverseClient

{
public static void main(String args[])

Reverse obj = null;

try
{

// initialize the ORB

ORB orb = [Link](args, null);

// get reference to NameService

[Link] objRef =

orb.resolve_initial_references("NameService");

NamingContextExt ncRef =

[Link](objRef);
// resolve object

String name = "Reverse";

obj = [Link](ncRef.resolve_str(name));

// take input

BufferedReader br =

new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter The String=");


String str = [Link]();

// call remote method

String result = obj.reverse_string(str);

[Link]("Reversed String= " + result);

catch(Exception e)

{
[Link]("ERROR : " + e);

[Link]();

}
}

//[Link]
import ReverseModule.*;

import [Link].*;

import [Link].*;

class ReverseImpl extends ReversePOA

public ReverseImpl()

super();
}

public String reverse_string(String name)

StringBuffer str = new StringBuffer(name);

return [Link]().toString();

//[Link]
module ReverseModule {

interface Reverse {

string reverse_string(in string name);

};

};
OUTPUT:
Source code:
import [Link];

public class ScatterGather {

public static void main(String args[]) {

[Link](args);

int rank = MPI.COMM_WORLD.Rank();

int size = MPI.COMM_WORLD.Size();


int root = 0;

int sendbuf[] = null;

sendbuf = new int[size];

if (rank == root) {

sendbuf[0] = 10;

sendbuf[1] = 20;

sendbuf[2] = 30;
sendbuf[3] = 40;

[Link]("Processor " + rank + " has data: ");

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

[Link](sendbuf[i] + " ");

[Link]();

}
int recvbuf[] = new int[1];
MPI.COMM_WORLD.Scatter(sendbuf, 0, 1, [Link],

recvbuf, 0, 1, [Link], root);

[Link]("Processor " + rank + " has data: " + recvbuf[0]);

[Link]("Processor " + rank + " is doubling the data");

recvbuf[0] = recvbuf[0] * 2;

MPI.COMM_WORLD.Gather(recvbuf, 0, 1, [Link],

sendbuf, 0, 1, [Link], root);


if (rank == root) {

[Link]("Process 0 has data: ");

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

[Link](sendbuf[i] + " ");


}

[Link]();

[Link]();

OUTPUT:
Source code:
// Server program:
import socket

import threading

from datetime import datetime, timedelta

clients = []

client_times = []
def handle_client(conn, addr):

print(f"Client Data updated with: {addr[0]} : {addr[1]}")

[Link](conn)

# receive client time

client_time_str = [Link](1024).decode()

client_time = [Link](client_time_str, "%Y-%m-%d %H:%M:%S.%f")

client_times.append((conn, client_time))
def synchronize():

print("\nNew synchronization cycle started.")

print(f"Number of clients to be synchronized: {len(client_times)}")

# master time

master_time = [Link]()

# calculate average time

total_time = master_time.timestamp()
for _, ct in client_times:
total_time += [Link]()

avg_time = total_time / (len(client_times) + 1)

avg_datetime = [Link](avg_time)

print("Recent time sent successfully")

# send adjustment to clients

for conn, ct in client_times:

diff = avg_datetime - ct
[Link](str(diff.total_seconds()).encode())

def start_server():

server = [Link](socket.AF_INET, socket.SOCK_STREAM)

[Link](("[Link]", 5000))
[Link](5)

print("Server started...\n")

threads = []

# accept 3 clients

for _ in range(3):

conn, addr = [Link]()

t = [Link](target=handle_client, args=(conn, addr))

[Link]()
[Link](t)

for t in threads:

[Link]()

synchronize()

[Link]()

if __name__ == "__main__":

start_server()

// Client Program:
import socket

from datetime import datetime, timedelta

def start_client():

client = [Link](socket.AF_INET, socket.SOCK_STREAM)

[Link](("[Link]", 5000))
# send current time

local_time = [Link]()

[Link](str(local_time).encode())
# receive adjustment

diff = float([Link](1024).decode())

new_time = local_time + timedelta(seconds=diff)

print("Synchronized time at the client is :", new_time)


[Link]()

if __name__ == "__main__":

start_client()

OUTPUT:
Source Code :

import [Link].*;
class TokenRing {

public static void main(String args[]) {

Scanner scan = new Scanner([Link]);

[Link]("Enter the num of nodes:");

int n = [Link]();

int token = 0;

// Display ring
for (int i = 0; i < n; i++) {

[Link](i + " ");

[Link]("0");

[Link]("\nEnter sender:");

int s = [Link]();
[Link]("Enter receiver:");

int r = [Link]();

[Link]("Enter Data:");

int data = [Link]();

// Token Passing

[Link]("Token passing: ");

int i = token;

while (i != s) {
[Link](i + "->");

i = (i + 1) % n;

[Link](s);
// Sender sends data

[Link]("Sender " + s + " sending data: " + data);

// Forwarding

i = (s + 1) % n;
while (i != r) {

[Link]("data " + data + " forwarded by " + i);

i = (i + 1) % n;

// Receiver

[Link]("Receiver " + r + " received data: " + data);

[Link]();

}
}

OUTPUT:
Source code:
// [Link]:
import [Link].*;

class Process {

int id;

String state;

public class Ring {

public static void main(String[] args) {


Scanner in = new Scanner([Link]);

[Link]("Enter the number of process : ");

int n = [Link]();

Process proc[] = new Process[n];

// initialize processes

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

proc[i] = new Process();


}

// input process IDs

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

[Link]("Enter the id of process : ");

proc[i].id = [Link]();

proc[i].state = "active";

}
// sort processes by ID

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (proc[j].id > proc[j + 1].id) {

int temp = proc[j].id;

proc[j].id = proc[j + 1].id;


proc[j + 1].id = temp;

}
while (true) {

[Link]("\[Link] [Link]");

int choice = [Link]();

if (choice == 2) {

[Link]("Program terminated ...");

break;

[Link]("\nEnter the Process number who initialised election : ");


int init = [Link]();

int pos = -1;

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

if (proc[i].id == init) {

pos = i;

break;

}
}

if (pos == -1) {

[Link]("Invalid process!");

continue;

int maxId = proc[pos].id;

int current = pos;


do {

int next = (current + 1) % n;

[Link]("Process " + proc[current].id +


" send message to " + proc[next].id);

if (proc[next].id > maxId) {

maxId = proc[next].id;

}
current = next;

} while (current != pos);

[Link]("process " + maxId + " selected as co-ordinator");

OUTPUT:
// [Link]:
import [Link];

public class Bully {

static boolean[] state = new boolean[5];

static int coordinator;

// Election process
public static void up(int up) {

if (up < 1 || up > 5) {

[Link]("Invalid process number!");

return;

}
if (state[up - 1]) {

[Link]("process " + up + " is already up");


} else {

state[up - 1] = true;

[Link]("process " + up + " held election");

for (int i = up; i < 5; i++) {

[Link]("election message sent from process " + up + " to process " + (i +


1));

for (int i = 4; i >= 0; i--) {

if (state[i]) {

coordinator = i + 1;
break;

[Link]("Process " + coordinator + " is coordinator");

}
// Bring process down

public static void down(int down) {

if (down < 1 || down > 5) {

[Link]("Invalid process number!");


return;

if (!state[down - 1]) {

[Link]("process " + down + " is already down");

} else {

state[down - 1] = false;

[Link]("process " + down + " is now down");

}
}

// Send message

public static void message(int mess) {

if (!state[mess - 1]) {

[Link]("process " + mess + " is down");

return;

}
if (mess == coordinator) {

[Link]("OK");

} else {

[Link]("process " + mess + " election");

for (int i = mess; i < 5; i++) {

[Link]("election send from process " + mess + " to process " + (i + 1));

}
for (int i = 4; i >= 0; i--) {

if (state[i]) {

coordinator = i + 1;
break;

[Link]("Coordinator message sent from process " + coordinator + " to all");


}

public static void main(String args[]) {

Scanner sc = new Scanner([Link]);

// Initially all processes are up

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

state[i] = true;

}
coordinator = 5;

[Link]("Processes up = p1 p2 p3 p4 p5");

[Link]("Process 5 is coordinator");

while (true) {

[Link]("\n1 up a process");

[Link]("2 down a process");

[Link]("3 send a message");


[Link]("4 Exit");

int choice = [Link]();

switch (choice) {

case 1:

[Link]("Bring up which process: ");

int up = [Link]();

up(up);
break;

case 2:

[Link]("Bring down any process: ");


int down = [Link]();

down(down);

break;

case 3:
[Link]("Which process will send message: ");

int msg = [Link]();

message(msg);

break;

case 4:

[Link](0);

}
}
OUTPUT:

You might also like