0% found this document useful (0 votes)
4 views

DS report file

Very informative Xkgxkyditditzitsitsitditdtodtodoyf66t
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)
4 views

DS report file

Very informative Xkgxkyditditzitsitsitditdtodtodoyf66t
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
You are on page 1/ 23

FACULTY OF ENGINEERING &

TECHNOLOGY
AGRA COLLEGE, AGRA

DISTRIBUTED SYSTEM LAP REPORT FILE


(KCS077)

Submitted To: Submitted By:


Dr.ANURAG SHARMA YOGESH KUMAR
H.O.D (Computer Science & B.Tech (4rd Year)
Engineering) (2100020100117)
1. Simulate the functioning of Lamport's Logical Clock in JAVA.
import java.util.*;
class Process {
private int id;
private int logicalClock;
public Process(int id) {
this.id = id;
this.logicalClock = 0;
}
public int getId() {
return id;
}
public int getLogicalClock() {
return logicalClock;
}
public void tick() {
logicalClock++;
}
public void receiveMessage(int senderClock) {
logicalClock = Math.max(logicalClock, senderClock) + 1;
}
@Override
public String toString() {
return "Process " + id + " (Clock: " + logicalClock + ")";
}
}
class Event {
private Process sender;
private Process receiver;
public Event(Process sender, Process receiver) {
this.sender = sender;
this.receiver = receiver;
}
public void execute() {
sender.tick();
int senderClock = sender.getLogicalClock();
receiver.receiveMessage(senderClock);

System.out.println(sender + " sent a message to " + receiver);


System.out.println("Updated " + receiver);
}
}
public class LamportLogicalClock {
public static void main(String[] args) {
Process p1 = new Process(1);
Process p2 = new Process(2);
Process p3 = new Process(3);
List<Event> events = new ArrayList<>();
events.add(new Event(p1, p2));
events.add(new Event(p2, p3));
events.add(new Event(p3, p1));
events.add(new Event(p2, p1));
events.add(new Event(p1, p3));
System.out.println("Initial state:");
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
System.out.println();
for (Event event : events) {
event.execute();
System.out.println();
}
System.out.println("Final state:");
System.out.println(p1);
System.out.println(p2);
System.out.println(p3);
}
}
// Run the simulation
LamportLogicalClock.main(null);
2. Simulate the Distributed Mutual Exclusion in JAVA.
import java.util.Random;

public class DistributedMutualExclusion {

private static final int NUM_PROCESSES = 5;

private static final int MAX_REQUESTS = 10;

private static Process[] processes;

private static int totalRequests = 0;

private static Random random = new Random();

static class Process {

int id;

int timestamp;

boolean requesting;

boolean inCS;

boolean[] deferReplies;

Process(int id) {

this.id = id;

this.timestamp = 0;

this.requesting = false;

this.inCS = false;

this.deferReplies = new boolean[NUM_PROCESSES];

public static void main(String[] args) {

initializeProcesses();

simulateDistributedMutualExclusion();

}
private static void initializeProcesses() {

processes = new Process[NUM_PROCESSES];

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

processes[i] = new Process(i);

private static void simulateDistributedMutualExclusion() {

while (totalRequests < MAX_REQUESTS) {

int processId = random.nextInt(NUM_PROCESSES);

if (!processes[processId].requesting && !processes[processId].inCS) {

requestCriticalSection(processId);

} else if (processes[processId].inCS) {

releaseCriticalSection(processId);

// Simulate message passing and handling

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

if (i != processId) {

handleRequest(processId, i);

handleReply(i, processId);

printSystemState();

private static void requestCriticalSection(int processId) {

processes[processId].requesting = true;

processes[processId].timestamp = totalRequests;

System.out.printf("Process %d is requesting critical section (TS: %d)%n", processId,


processes[processId].timestamp);
}

private static void releaseCriticalSection(int processId) {

processes[processId].inCS = false;

processes[processId].requesting = false;

System.out.printf("Process %d is releasing critical section%n", processId);

// Send deferred replies

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

if (processes[processId].deferReplies[i]) {

processes[processId].deferReplies[i] = false;

System.out.printf("Process %d sends deferred reply to Process %d%n", processId, i);

totalRequests++;

private static void handleRequest(int senderId, int receiverId) {

if (processes[receiverId].inCS ||

(processes[receiverId].requesting &&

processes[receiverId].timestamp < processes[senderId].timestamp)) {

processes[receiverId].deferReplies[senderId] = true;

System.out.printf("Process %d defers reply to Process %d%n", receiverId, senderId);

} else {

System.out.printf("Process %d sends reply to Process %d%n", receiverId, senderId);

private static void handleReply(int senderId, int receiverId) {

if (processes[receiverId].requesting) {

boolean canEnter = true;

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


if (i != receiverId && processes[receiverId].deferReplies[i]) {

canEnter = false;

break;

if (canEnter) {

processes[receiverId].inCS = true;

processes[receiverId].requesting = false;

System.out.printf("Process %d enters critical section%n", receiverId);

private static void printSystemState() {

System.out.println("\nSystem State:");

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

System.out.printf("Process %d: %s %s%n", i,

processes[i].requesting ? "Requesting" : "Not Requesting",

processes[i].inCS ? "In CS" : "Not In CS");

System.out.println();

}
3. Implement a Distributed Chat Server using TCP Sockets in JAVA
SERVER.JAVA

import java.io.*;

import java.net.*;

import java.util.*;

public class Server {

private static final int PORT = 5000;

private static HashSet<PrintWriter> writers = new HashSet<>();

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

System.out.println("The chat server is running...");

ServerSocket listener = new ServerSocket(PORT);

try {

while (true) {

new ClientHandler(listener.accept()).start();

} finally {

listener.close();

private static class ClientHandler extends Thread {

private String name;

private Socket socket;

private BufferedReader in;

private PrintWriter out;

public ClientHandler(Socket socket) {


this.socket = socket;

public void run() {

try {

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

while (true) {

out.println("SUBMITNAME");

name = in.readLine();

if (name == null) {

return;

synchronized (writers) {

if (!writers.contains(out)) {

out.println("NAMEACCEPTED");

writers.add(out);

break;

while (true) {

String input = in.readLine();

if (input == null) {

return;

for (PrintWriter writer : writers) {

writer.println("MESSAGE " + name + ": " + input);

}
}

} catch (IOException e) {

System.out.println(e);

} finally {

if (name != null) {

System.out.println(name + " is leaving");

if (out != null) {

writers.remove(out);

try {

socket.close();

} catch (IOException e) {

CLIENT.JAVA

import java.awt.event.*;

import java.io.*;

import java.net.*;

import javax.swing.*;

public class Client {

BufferedReader in;

PrintWriter out;

JFrame frame = new JFrame("Chatter");

JTextField textField = new JTextField(40);

JTextArea messageArea = new JTextArea(8, 40);


public Client() {

textField.setEditable(false);

messageArea.setEditable(false);

frame.getContentPane().add(textField, "North");

frame.getContentPane().add(new JScrollPane(messageArea), "Center");

frame.pack();

textField.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

out.println(textField.getText());

textField.setText("");

});

private String getServerAddress() {

return JOptionPane.showInputDialog(

frame,

"Enter IP Address of the Server:",

"Welcome to the Chatter",

JOptionPane.QUESTION_MESSAGE);

private String getName() {

return JOptionPane.showInputDialog(

frame,

"Choose a screen name:",

"Screen name selection",

JOptionPane.PLAIN_MESSAGE);

}
private void run() throws IOException {

String serverAddress = getServerAddress();

Socket socket = new Socket(serverAddress, 5000);

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

while (true) {

String line = in.readLine();

if (line.startsWith("SUBMITNAME")) {

out.println(getName());

} else if (line.startsWith("NAMEACCEPTED")) {

textField.setEditable(true);

} else if (line.startsWith("MESSAGE")) {

messageArea.append(line.substring(8) + "\n");

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

Client client = new Client();

client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

client.frame.setVisible(true);

client.run();

}
4. Implement Java RMI" mechanism for accessing methods of remote
systems
CalculatorService.java (Remote Interface)

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface CalculatorService extends Remote {

int add(int a, int b) throws RemoteException;

int subtract(int a, int b) throws RemoteException;

int multiply(int a, int b) throws RemoteException;

int divide(int a, int b) throws RemoteException;

CalculatorServiceImpl.java (Remote Object Implementation)

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

public class CalculatorServiceImpl extends UnicastRemoteObject implements


CalculatorService {

public CalculatorServiceImpl() 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) {

throw new RemoteException("Division by zero");

return a / b;

CalculatorServer.java (RMI Server)

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class CalculatorServer {

public static void main(String[] args) {


try {

// Create and export the remote object

CalculatorService calculator = new CalculatorServiceImpl();

// Create and start the RMI registry on port 1099

Registry registry = LocateRegistry.createRegistry(1099);

// Bind the remote object to the registry

registry.rebind("CalculatorService", calculator);

System.out.println("Calculator Server is running...");

} catch (Exception e) {

System.err.println("Server exception: " + e.toString());

e.printStackTrace();

CalculatorClient.java (RMI Client)

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

public class CalculatorServer {

public static void main(String[] args) {

try {

// Create and export the remote object

CalculatorService calculator = new CalculatorServiceImpl();


// Create and start the RMI registry on port 1099

Registry registry = LocateRegistry.createRegistry(1099);

// Bind the remote object to the registry

registry.rebind("CalculatorService", calculator);

System.out.println("Calculator Server is running...");

} catch (Exception e) {

System.err.println("Server exception: " + e.toString());

e.printStackTrace();

CalculatorService.java (Remote Interface)

```java project="JavaRMIExample" file="CalculatorService.java"

CalculatorServiceImpl.java (Remote Object Implementation)

java project="JavaRMIExample" file="CalculatorServiceImpl.java"

CalculatorServer.java (RMI Server)

java project="JavaRMIExample" file="CalculatorServer.java"

CalculatorClient.java (RMI Client)

java project="JavaRMIExample" file="CalculatorClient.java"


5. Simulate Balanced Sliding Window Protocol in JAVA.
import java.util.*;

public class BalancedSlidingWindowProtocol {

private static final int TOTAL_PACKETS = 20;

private static final int INITIAL_WINDOW_SIZE = 4;

private static final double PACKET_LOSS_PROBABILITY = 0.2;

private static final int TIMEOUT = 5;

private static class Sender {

int base;

int nextSeqNum;

int windowSize;

boolean[] acked;

Timer[] timers;

Sender() {

base = 0;

nextSeqNum = 0;

windowSize = INITIAL_WINDOW_SIZE;

acked = new boolean[TOTAL_PACKETS];

timers = new Timer[TOTAL_PACKETS];

void send(Receiver receiver) {

while (nextSeqNum < base + windowSize && nextSeqNum < TOTAL_PACKETS) {

if (Math.random() > PACKET_LOSS_PROBABILITY) {

System.out.println("Sender: Sending packet " + nextSeqNum);

receiver.receive(nextSeqNum);

} else {
System.out.println("Sender: Packet " + nextSeqNum + " lost");

startTimer(nextSeqNum);

nextSeqNum++;

void startTimer(int seqNum) {

timers[seqNum] = new Timer();

timers[seqNum].schedule(new TimerTask() {

@Override

public void run() {

handleTimeout(seqNum);

}, TIMEOUT * 1000);

void handleTimeout(int seqNum) {

System.out.println("Sender: Timeout for packet " + seqNum);

nextSeqNum = seqNum;

send(null); // Resend from the timed-out packet

void receiveAck(int ackNum) {

System.out.println("Sender: Received ACK for packet " + ackNum);

acked[ackNum] = true;

if (ackNum == base) {

while (base < TOTAL_PACKETS && acked[base]) {

if (timers[base] != null) {

timers[base].cancel();
}

base++;

adjustWindow(true);

void adjustWindow(boolean increase) {

if (increase && windowSize < TOTAL_PACKETS) {

windowSize++;

System.out.println("Sender: Increasing window size to " + windowSize);

} else if (!increase && windowSize > 1) {

windowSize--;

System.out.println("Sender: Decreasing window size to " + windowSize);

private static class Receiver {

int expectedSeqNum;

int windowSize;

Receiver() {

expectedSeqNum = 0;

windowSize = INITIAL_WINDOW_SIZE;

void receive(int seqNum) {

if (seqNum == expectedSeqNum) {

System.out.println("Receiver: Received packet " + seqNum);


sendAck(seqNum);

expectedSeqNum++;

adjustWindow(true);

} else if (seqNum > expectedSeqNum) {

System.out.println("Receiver: Received out-of-order packet " + seqNum);

sendAck(expectedSeqNum - 1);

adjustWindow(false);

} else {

System.out.println("Receiver: Received duplicate packet " + seqNum);

sendAck(seqNum);

void sendAck(int ackNum) {

System.out.println("Receiver: Sending ACK for packet " + ackNum);

// In a real implementation, this would send the ACK back to the sender

void adjustWindow(boolean increase) {

if (increase && windowSize < TOTAL_PACKETS) {

windowSize++;

System.out.println("Receiver: Increasing window size to " + windowSize);

} else if (!increase && windowSize > 1) {

windowSize--;

System.out.println("Receiver: Decreasing window size to " + windowSize);

public static void main(String[] args) {


Sender sender = new Sender();

Receiver receiver = new Receiver();

while (sender.base < TOTAL_PACKETS) {

sender.send(receiver);

// Simulate ACKs being received (with some delay and possible loss)

for (int i = sender.base; i < sender.nextSeqNum; i++) {

if (Math.random() > PACKET_LOSS_PROBABILITY) {

try {

Thread.sleep((int) (Math.random() * 1000)); // Random delay

} catch (InterruptedException e) {

e.printStackTrace();

sender.receiveAck(i);

try {

Thread.sleep(1000); // Wait a bit before next send

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Transmission complete!");

}
6. Implement CORBA mechanism by using C++program at one end
and Java program on the other.

Define the IDL File:

// Filename: Hello.idl

module HelloApp {
interface Hello {
string say_hello();
};
};

C++ Side (Server):

// HelloServer.cpp

#include "Hello.hh" // Generated by the IDL compiler


#include <tao/ORB.h>
#include <ace/Log_Msg.h>

class HelloImpl : public virtual POA_HelloApp::Hello {


public:
HelloImpl() {}
virtual ~HelloImpl() {}

virtual char* say_hello() {


return CORBA::string_dup("Hello from C++ CORBA Server!");
}
};

int main(int argc, char* argv[]) {


try {
// Initialize the ORB
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);

// Create an object servant


HelloImpl hello_impl;

// Obtain the root POA and activate the servant


CORBA::Object_var root_poa_object = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var root_poa =
PortableServer::POA::_narrow(root_poa_object.in());

PortableServer::ServantBase_var owner_transfer = hello_impl._this();

// Run the ORB event loop


orb->run();
}
catch (const CORBA::Exception& ex) {
ex._tao_print_exception("Exception caught in C++ server:");
return 1;
}
return 0;
}

Java Side (Client):

// HelloClient.java

import HelloApp.*;

public class HelloClient {


public static void main(String[] args) {
try {
// Initialize the ORB
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args, null);

// Get the object reference of the server


org.omg.CORBA.Object obj =
orb.string_to_object("corbaloc:iiop:localhost:12345/Hello");

// Narrow the object reference to the Hello interface


Hello hello = HelloHelper.narrow(obj);

// Call the method on the server


System.out.println(hello.say_hello());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Run the Server and Client:

Run the C++ server:

Compile the C++ server code (HelloServer.cpp) and run it:

g++ -o HelloServer HelloServer.cpp -lTAO -lACE


./HelloServer

Run the Java client:

Compile the Java client code (HelloClient.java) and run it:

javac HelloClient.java
java HelloClient

You might also like