You are on page 1of 18

Institute of Engineering & Technology

Bundelkhand University, Jhansi

Distributed System Programming Lab


File
Submitted to Department of Computer Science & Engineering

Session 2019-2020

Submitted To: Submitte By:

Dr.Lalit Kumar Gupta Saumya katiyar

I.E.T.BU;Jhansi (161381030040)
CONTENTS
S.No. Program Page no.
1. Design and implemention RMI using Java 3
2. Design and implemention of a sequencer 6
multicast protocol using java

3. Design and implemention of a Task Bag Server 9


using CORBA or java RMI

4. Use of unix interface to UDP sockets to 10


implement a simple RPC framework in C++

5. Operating System Experiments 13


6. A proto type for stateless file server and its 16
cache mechanism

2
Program -1
Design and implemention RMI using Java
 Step1: Creating a Search  interface
// Creating a Search interface
import java.rmi.*;
public interface Search extends Remote
{
    // Declaring the method prototype
    public String query(String search) throws RemoteException;
}
Step 2: Implementing the remote interface
// Java program to implement the Search interface
import java.rmi.*;
import java.rmi.server.*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
    // Default constructor to throw RemoteException
    // from its parent constructor
    SearchQuery() throws RemoteException
    {
        super();
    }
  
    // Implementation of the query interface
    public String query(String search) throws RemoteException
    {
        String result;
        if (search.equals("Reflection in Java"))
            result = "Found";
        else
            result = "Not Found";
  
        return result;
    }
}
Step 3:  Creating Stub and Skeleton objects from the implementation class using rmic

STEP 4: Start the rmiregistry

STEP 5: Create and execute the server application program

//program for server application


import java.rmi.*;
import java.rmi.registry.*;
public class SearchServer
{

3
    public static void main(String args[])
    {
        try
        {
            // Create an object of the interface
            // implementation class
            Search obj = new SearchQuery();
  
            // rmiregistry within the server JVM with
            // port number 1900
            LocateRegistry.createRegistry(1900);
  
            // Binds the remote object by the name
            // geeksforgeeks
            Naming.rebind("rmi://localhost:1900"+"/geeksforge
eks",obj);
        }
        catch(Exception ae)
        {
            System.out.println(ae);
        }
    }
}
Step 6: Create and execute the client application program

//program for client application


import java.rmi.*;
public class ClientRequest
{
    public static void main(String args[])
    {
        String answer,value="Reflection in Java";
        try
        {
            // lookup method to find reference of remote
object
            Search access =
                (Search)Naming.lookup("rmi://localhost:1900"+
"/geeksforgeeks");
            answer = access.query(value);
            System.out.println("Article on " + value + " " +
answer+" at GeeksforGeeks");
        }
        catch(Exception ae)
        {
            System.out.println(ae);
        }
    }
}

4
5
Program -2
Design and implemention of a sequencer multicast protocol
using java
Sequencer.java (complete)

package sequencer;

import java.rmi.*;
import java.net.*;
import java.io.*;

public interface Sequencer extends Remote


{
    // join -- request for "sender" to join sequencer's multicasting service;
    // returns an object specifying the multicast address and the first sequence number to
expect
    public SequencerJoinInfo join(String sender)  throws RemoteException,
SequencerException;

  // send -- "sender" supplies the msg to be sent, its identifier,


    // and the sequence number of the last received message
   public void send(String sender, byte[] msg, long msgID, long lastSequenceReceived)
        throws RemoteException;

    // leave -- tell sequencer that "sender" will no longer need its services
   public void leave(String sender) throws RemoteException;

    // getMissing -- ask sequencer for the message whose sequence number is "sequence"
   public byte[] getMissing(String sender, long sequencer)throws RemoteException,
SequencerException;

    // heartbeat -- we have received messages up to number "lastSequenceReceived"


   public void heartbeat(String sender, long lastSequenceReceived)throws RemoteException;
}
 

SequencerJoinInfo.java (complete)

package sequencer;

import java.io.*;
import java.net.*;

public class SequencerJoinInfo implements Serializable


{

6
    public InetAddress addr;
    public long sequence;

    public SequencerJoinInfo(InetAddress addr, long sequence)


    {
        this.addr = addr;
        this.sequence = sequence;
    }
}
 
 SequencerException.java (complete)

package sequencer;

import java.io.*;

public class SequencerException extends Exception implements Serializable


{
    public SequencerException(String s)
    {
        super(s);
    }
}
 
 Group.java (outline only)

package sequencer;

import java.net.*;
import java.util.*;
import java.io.*;
import java.rmi.*;

public class Group implements Runnable


{

    public Group(String host, MsgHandler handler, String senderName)  throws


GroupException
    {
       // contact Sequencer on "host" to join group,
       // create MulticastSocket and thread to listen on it,
       // perform other initialisations
    }

    public void send(byte[] msg) throws GroupException


    {
        // send the given message to all instances of Group using the same sequencer
    }

7
    public void leave()
    {
       // leave group
    }

    public void run()


    {
        // repeatedly: listen to MulticastSocket created in constructor, and on receipt
        // of a datagram call "handle" on the instance
        // of Group.MsgHandler which was supplied to the constructor
    }

    public interface MsgHandler


    {
         public void handle(int count, byte[] msg);
    }

    public class GroupException extends Exception


    {
        public GroupException(String s)
        {
            super(s);
        }
    }

    public class HeartBeater extends Thread


    {
        // This thread sends heartbeat messages when required
    }

}
 

8
Program-3
Design and implemention of a Task Bag Server using CORBA
or java RMI
 
 
module tasks
{
  interface TaskReadyCallback
  {
    oneway void taskReady();  
  };
 
  interface TaskMasterControllerCallbacks
  {
    oneway void taskStarted(in string workerName, in string task);
    oneway void taskFinished(in string workerName, in string task);
    oneway void addWorker(in string workerName);
    oneway void removeWorker(in string workerName);
  };
 
  interface TaskBag
  {
    oneway void pairOut(in string key, in string value);  
    oneway void pairOutTask(in string key, in string value);
    oneway void pairOutResult(in string key, in string value, in string workerName);
    string pairIn(in string key);
    string pairInTask(in string key, in string workerName);
    string readPair(in string key);
   
    void clear();
    void registerTaskMasterCallbacks(in TaskMasterControllerCallbacks callback);
    void addWorker(in string workerName, in TaskReadyCallback callback);
    void removeWorker(in string workerName);
  };
};

9
Program-4
Use of unix interface to UDP sockets to implement a simple
RPC framework in C++

class Message {
public:
Message(unsigned char *, unsigned int ); // message and
length supplied
Message(unsigned int ); // length supplied
private:
unsigned char * data;
unsigned int length;
};

class Socket {
public:

Socket();
Socket(int); // port given as argument
status UDPsend(UDPMessage *m, SocketAddress *
destination);
status UDPreceive(UDPMessage **m, SocketAddress *
origin);
private:
int s;
SocketAddress * socketAddress;
};

class Client: public Socket {


public:
Client(); // calls constructor Socket()
status DoOperation (UDPMessage *callMessage, UDPMessage
*replyMessage, SocketAddress * server);
}; 
class Server: public Socket {
public:
Server(int); // calls constructor
Socket(int);
status GetRequest (UDPMessage *callMessage,
SocketAddress * client);

10
status SendReply (UDPMessage *replyMessage,
SocketAddress * client);
};

A class for RPC messages:

enum MessageType { Request, Reply};


class RPCMessage{
public:
RPCMessage(MessageType);
RPCMessage(MessageType, int, int, int);
void marshall( Message ** ); //
marshalls self to Message argument
void unmarshall(Message *); //
unmarshalls from given message to self
private:
MessageType type;
unsigned int requestId;
unsigned int procedureId; // e.g.(1,2,3,4)
for (+, -, *, /)
int arg1, arg2; // arguments/
return parameters
};
#include "/import/GCC/lib/g++-include/sys/socket.h"

You may also need the following:

extern "C" {
char * inet_ntoa(struct in_addr);
}
The prototypes for DoOperation, GetRequest and SendReply (to which you must adhere)
are as follows:
Status DoOperation (Message *message, Message *reply,
int s, SocketAddress serverSA);
Status GetRequest (Message *callMessage, int s,
SocketAddress *clientSA);
Status SendReply (Message *replyMessage, int s,
SocketAddress clientSA);
The prototypes for UDPsend and UDPreceive are as follows:
Status UDPsend(int s, Message *m, SocketAddress
destination);
Status UDPreceive(int s, Message *m, SocketAddress
*origin);

11
Program-5
Operating System Experiments
1 Timing
Do apropos time to obtain a list of all commands, system calls and library calls related to the
topic of time. Take a while to browse documentation on some of these, using
the man command.

2 Measuring System Call Time


Suppose you are timing a repeatable operation, such as the getpid system call, which you
have reason to believe is of smaller or equal duration to the resolution of the system clock.

3 Measuring Process Creation Time


There is only one way to create a new process under UNIX: the fork system call. Do man
fork to find out about it. Do man exit to find out how a process can terminate itself. Do man
wait to find out how a parent can await its children's termination.

Produce a modified version of the fork+wait program, so that each child process execs fred.
Attach this program. Run this program several times and record the values obtained.

4 Exploring the Address Space


Do man size to find out about this command. Use size with appropriate options on a
binary fred to find out as much as you can about the layout of code and data for fred.

Input the following simple program, compile it, use size on the binary and convert size’s
output to hexadecimal representation.
static char *aStaticString = "fred";
static int aStaticDataItem;
static int anInitialisedStaticDataItem = 0x666;
main(int argc, char *argv[])
{
    unsigned char *cp;
    unsigned char aCharacter;
    cp = &aCharacter;
    printf("address of character on stack = 0x%x\n", cp);
    printf("address of initialised string = 0x%x\n", aStaticString );
    printf("address of uninitialised int = 0x%x\n", &aStaticDataItem);
    printf("address of initialised int = 0x%x\n", &anInitialisedStaticDataItem);
    printf("address of procedure main = 0x%x\n", main);
}
4.1 Apart from the address of aCharacter, account for the address values printed by this
program, relating them to the output of size.
 

12
4.2 Discuss whether you have sufficient evidence to determine the top of the stack’s address
range.
Add the following code to the program above.
for(cp = &aCharacter; ; cp -= PAGESIZE) /* you need to #define PAGESIZE */
{
    aCharacter = *cp;
    printf("made it to 0x%x!\n", cp);
}

6 Inter-process, intra-machine invocation


The program cliserv_rpc.c, when given "client" as an argument repeatedly calls sendto with
a dummy data argument of size datasize (given as another program argument), followed
by recvfrom with a 4-byte data argument. When given "server" as an argument it repeatedly
calls recvfrom with a data argument of size datasize (given as the second program
argument), then sends a reply using sendto with a 4-byte data argument. Note that this
server does not perform any useful processing upon the arriving ‘requests’. Nor does it do a
lookup to identify a (dummy) procedure or ‘method’ to call. Use some sensible port number
for the server, unique on the machine.

Run a client and server together at the same machine, and test that they work together.

7 Inter-machine invocation
Run the server program and the client program between two different, dedicated machines.

7.2 send to uses UDP. This places an 8-byte header onto an IP packet, which in turn uses a
20-byte header. An Ethernet packet carries 18 bytes of its own header and checksum. The
minimum Ethernet packet size is 64 bytes. Ethernet bandwidth is 10 or 100 Mbits/sec (find
out about your Ethernet).

8 Inter-machine asynchronous invocation


Adapt the previous program to produce the following. As a client, the program repeatedly
calls sendto ? but not recvfrom. As a server, it repeatedly calls recvfrom ? and does not
reply. Make the server report if any messages are lost.

Run a client and server at separate, dedicated machines. NB You may find that sendto fails
for lack of buffer space after a certain number of sends. Try to accommodate this by reducing
the number of attempted sends each time.

9 TCP and Connected Sockets


Adapt the program cliserv_rpc.c so that the client and server use a single pair
of connected sockets for request-reply communication. NB It is a good idea to use the
call setsockopt before calling bind on the socket you will use to accept a connection. This

13
avoids a problem of your program not working because the bound address otherwise stays
"in use" for a considerable time after the program has terminated:

     int option = 1;


     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
 

14
Program-6
A proto type for stateless file server and its cache
mechanism

Introduction
This project concerns the design and implementation of a simple stateless file
server and its client-side API. It will give you experience in the use of TCP for
communication between client and server and in the design of a client-side
cache.The interface of the client-side API (which you should implement) is
provided below, together with a default client and a data file with which you can
test your software.
The Java interface for the client API for the file system
/* This is the interface to the client-side file system. We assume
that, once you open the file, you keep a pointer, and whenever
you write or read, that pointer moves to the next byte. */

/* I hide the representation of the "filehandle" (given in a separate


class file). You can change its implementation as you like. */

import filehandle;

public interface fileSystemAPI


{
/* url has form IP:port/path. */
public abstract filehandle open(String url)
throws java.io.IOException;

/* write data starting from the current pointer. */


public abstract boolean write(filehandle fh, byte[] data)
throws java.io.IOException;

/* read data.length bytes from the current position; if


end-of-fike, returns -1; if not, the next byte (position) is
returned. */
public abstract int read(filehandle fh, byte [] data)
throws java.io.IOException;

/* close file. you should flush the data (over the network). */
public abstract boolean close(filehandle fh)
throws java.io.IOException;

/* check if it is at the end-of-file. */


public abstract boolean isEOF(filehandle fh)
throws java.io.IOException;

/* You do not have to implement the following two methods. */


// public abstract boolean flush(filehandle fh);
// public abstract byte [] read(filehandle fh, int n);

15
}

The program used to check whether the filehandle class works correctly
import java.io.*;
import filehandle;

public class checkfh


{
public static void main(String argv[])
{
filehandle fh1, fh2;

fh1=new filehandle();
System.out.println("one made.");

if (fh1.isAlive())
System.out.println("one is alive.");

fh2=new filehandle();
System.out.println("two made.");
if (fh2.isAlive())
System.out.println("two is alive.");

if (fh1.Equals(fh2))
System.out.println("one and two are same, this is
strange..");
else
System.out.println("one and two are not equal.");
fh1.discard();
fh2.discard();
if (fh1.Equals(fh2))
System.out.println("one and two are discarded and are
equal.");
else
System.out.println("one and two are not equal, this is
strange.");
}
}
The client program is for testing the communication between client API and
the file server.
/* standard java classes. */
import java.io.*;
import java.util.*;

/* fileSystemAPI should be implemented by your client-side file system. */


import fileSystemAPI;
import filehandle;

/* There are two methods, main and readField. The latter does the
following.

(1) It reads one field upto, but not including, a specified delimiter.
(2) It also converts the byte array to String and returns it.
(3) The pointer should reside after the delimeter.

16
It does NOT expect the file can be in a wrong format... */

public class testClient{

public static void main(String [] args)


throws java.lang.InterruptedException, java.io.IOException
{
// get arguments.
String IPadr=args[0]; // e.g. 223.223.223.223
String Port=args[1]; // e.g. 7777
String Filename=args[2]; // e.g. MyFile

/* Initialise the client-side file system.


The following line should be replaced by something like:
FileSystemAPI fs=new YourClientSideFileSystem()
in your version.
*/
fileSystemAPI fs;

// variables used.
filehandle fh;
String city, weather, date, updatetime;
long startTime, endTime;
long turnAround;

// open file.
fh=fs.open(IPadr+":"+Port+"/"+Filename);

// repeat displaying remote data and turn-around time.

while (true){

// read the whole file, check the time needed.


startTime=Calendar.getInstance().getTime().getTime();

while (!fs.isEOF(fh)){

// read data.
city=readField(fs, fh, ';');
weather=readField(fs, fh, ';');
date=readField(fs, fh, ';');
updatetime=readField(fs, fh, '.');

// print data.
System.out.println(city+", "+weather+", "+date+",
"+updatetime);
}
endTime=Calendar.getInstance().getTime().getTime();
turnAround=endTime-startTime;

// print the turn around time.


System.out.println("");
System.out.println("This round takes"+turnAround+"ms.");

// wait a bit.
Thread.sleep(500);

17
/* We need to convert between bytes and chars. we do this by
simply getting ascii values and storing them as bytes.
*/

static String readField(fileSystemAPI fs, filehandle fh, char


delimeter)
throws java.lang.InterruptedException, java.io.IOException
{
/* This method reads a file byte-by-byte.
this is slow, but simple.
*/
char ch;
byte [] data = {(byte) 'a'};
int res;
String field="";
if (fs.isEOF(fh))
return null;
else {
while (true){
// reads one byte, and converts it into character.
res=fs.read(fh, data);
if (res==-1)
return field;
else {
ch=(char) data[0];
if (ch!=delimeter) {
field=field+(new Character(ch)).toString();
if (fs.isEOF(fh))
return field;
}
else
return field;
};
};
};
}
}

18

You might also like