dc lab manual

26
Distributed Computing 2013 1 LABORATORY MANUAL B.TECH (I.T) FINAL YEAR (7 TH SEMESTER) Distributed Computing (TIT-442) Govind Ballabh Pant University of Agriculture and Technology Department of Information Technology Pantnagar

Upload: shubham-bansal

Post on 28-Nov-2015

19 views

Category:

Documents


1 download

DESCRIPTION

$rap7cs lab manual

TRANSCRIPT

Distributed Computing 2013

1

LABORATORY MANUAL

B.TECH (I.T)

FINAL YEAR (7TH

SEMESTER)

Distributed Computing

(TIT-442)

Govind Ballabh Pant University of Agriculture and Technology

Department of Information Technology

Pantnagar

Distributed Computing 2013

2

INDEX S.No. Contents Page No.

1. To simulate the functioning of Lamport’s Logical Clock in ‘C’. 3-10

2. To simulate the functioning of Vector Logical Clock in ‘C’. 11-17

3. To simulate the Distributed Mutual Exclusion in ‘Java’. 18-21

4. To implement a Distributed Chat Server using TCP Sockets in

‘Java’.

22-26

5. To implement a Distributed Chat Server using UDP Sockets in

‘Java’.

27-30

6. To implement ‘Java RMI’ mechanism for accessing methods of

remote systems

31-34

7. Modeling a taskbar server using producer consumer in ‘Java’. 35-39

8. To implement concurrent echo client-server application. 40-45

9. To implement the persistence storage of PROBLEMs in ‘Java’. 46-49

10. To implement multicasting using multicast sender and multicast

sniffer in ‘Java’.

50-54

Program No.1

PROBLEM: To simulate the functioning of Lamport’s Logical Clock in ‘C’.

Theory:

Distributed Computing 2013

3

Lamport proposed a scheme to order the events in a distributed system by using logical clocks. Due to the

absence of synchronized clock and global time in a distributed system, the order in which events occur at

two different machines is impossible to be determined based on the local time at which they occurred.

Algorithm: This simulation takes place by using the following concepts.

1) Happened Before Relationship

2) Logical clocks

For any two events a & b, a is said to happened before b is denoted as a b, if they are in same process.

If events occur at different processes then for any message (m)

Send (m) Receive (m)

If a b and b c then a c i.e. is transitive.

If events casually affect each other then they are said to be casually related events a b

Two events are concurrent if a b and b a i.e. a||b

Conditions satisfied by Logical Clocks.

a) For any two events occurring on same process, a b if Ci[a] < Ci[b].

b) Clock Ci is implemented between any two events of the same process as Ci = Ci + d

(d>0)

c) If event a is sending message by process Pi and is received by process Pj, then tm =

Ci(a)

Cj = max(Cj+d, tm), d>0

Program:

#include<stdio.h>

#include<conio.h>

void time();

void timecheck(int,int);

int r[2][10];

int t1[10],t2[10];

int max(int,int);

void main()

{

int i,j,n=0,n1,n2;

clrscr();

printf("Enter the number of events of process1 :");

scanf("%d",&n1);

printf("for process 1\n:");

printf("\t Enter 0 for no message passing\n");

for(i=1;i<n1;i++)

{

printf("Event %d sends message to :",i);

scanf("%d",&n);

r[1][i]=n;

}

printf("Enter the number of events for the process2:");

scanf("%d",&n2);

printf("for process2\n");

printf("\t Enter 0 for no message passing\n");

Distributed Computing 2013

4

for(i=1;i<n2;i++)

{

printf("Event %d sends message to :",i);

scanf("%d",&n);

r[2][i]=n;

}

time();

timecheck(n1,n2);

printf("\n\n");

for(i=1;i<n1;i++)

{

if(r[1][i]!=0)

{

j=r[1][i];

printf("\nprocess1 sends message to event %d of process2 at time stamp %d",j,t1[i]);

printf("the updated time stamp of process 2 is %d",t2[j]);

}

}

for(i=1;i<n2;i++)

{

if(r[2][i]!=0)

{

j=r[2][i];

printf("\nprocess2 sends message to event %d of process1 at time stamp %d",j,t2[i]);

printf("the updated time stamp of process 2 is %d",t1[j]);

}

}

printf("\n\n");

printf("for process 1 time stamps are:\n");

printf("\n\t event \t timestamp");

for(i=1;i<n1;i++)

printf("\n\t%d\t\t%d",i,t1[i]);

printf("for process 2 time stamps are:\n");

printf("\n\t event \t timestamp");

for(i=1;i<n2;i++)

printf("\n\t%d\t\t%d",i,t2[i]);

getch();

}

void timecheck(int e1,int e2)

{

int i=1,j,m;

for(i=1;i<e1;i++)

{

for(j=1;j<e2;j++)

{

if((r[1][i])==j||(r[2][i]==j))

{

if(r[1][i]==j)

{

Distributed Computing 2013

5

t2[j]=max(t2[j],i+1);

for(m=j+1;m<e2;m++)

{

t2[m]=t2[m-1]+1;

}

}

else if(r[2][i]==j)

{

t1[j]=max(t1[j],i+1);

for(m=i+1;m<e1;m++)

{

t1[m]=t1[m-1]+1;

}

}

}

}

}

}

void time()

{

int i;

for(i=1;i<=10;i++)

{

t1[i]=i;

t2[i]=i;

}

}

int max(int a,int b)

{

if(a>=b)

return a;

else

return b;

}

Output of Lamport’s Clock enter the number of events of process1:5

for process1

enter 0 for no message passing

event 1 sends message to:0

event 2 sends message to:0

event 3 sends message to:0

event 4 sends message to:3

event 5 sends message to:0

enter the number of events of process2:4

for process2

Distributed Computing 2013

6

enter 0 for no message passing

event 1 sends message to:0

event 2 sends message to:0

event 3 sends message to:0

event 4 sends message to:0

process 1 sends message to event 3 of process 2 at time stamp 4 The

updated time stamp is of process 2 is 5

for process 1 time stamps are:

event timestamp

1 1

2 2

3 3

4 4

5 5

for process 2 time stamps are:

event timestamp

1 1

2 2

3 5

4 6

Program No.2

PROBLEM: To Simulate the functioning of Vector Logical Clock in ‘C’.

Program:

#include<stdio.h>

#include<conio.h>

void time();

void timecheck(int,int);

int max(int,int);

int r[2][10];

int t1[10],t2[10],v1[10],v2[10];

void main()

{

int i,j,n=0,n1,n2;

clrscr();

printf("Enter the number of events of process1 :");

scanf("%d",&n1);

printf("for process 1\n:");

printf("\t Enter 0 for no message passing\n");

for(i=1;i<n1;i++)

{

printf("Event %d sends message to :",i);

scanf("%d",&n);

r[1][i]=n;

}

printf("Enter the number of events for the process2:");

Distributed Computing 2013

7

scanf("%d",&n2);

printf("for process2\n");

printf("\t Enter 0 for no message passing\n");

for(i=1;i<n2;i++)

{

printf("Event %d sends message to :",i);

scanf("%d",&n);

r[2][i]=n;

}

time();

timecheck(n1,n2);

printf("\n\n");

for(i=1;i<n1;i++)

{

if(r[1][i]!=0)

{

j=r[1][i];

printf("\nprocess1 sends message to event %d of process2 at time stamp(%d %d)",j,t1[i],v1[i]);

printf("the updated time stamp of process 2 is (%d %d)",v2[j],t2[j]);

}

}

for(i=1;i<=n2;i++)

{

if(r[2][i]!=0)

{

j=r[2][i];

printf("\nprocess2 sends message to event %d of process1 at time stamp (%d %d)",j,v2[j],t2[i]);

printf("the updated time stamp of process 2 is (%d %d)",t1[j],v1[j]);

}

}

printf("\n\n");

printf("for process 1 time stamps are:\n");

printf("\n\t event \t timestamp");

for(i=1;i<n1;i++)

printf("\n\t%d\t\t(%d %d)",i,t1[i],v1[i]);

printf("for process 2 time stamps are:\n");

printf("\n\t event \t\t timestamp");

for(i=1;i<n2;i++)

printf("\n\t%d\t\t\t(%d %d)",i,v2[i],t2[i]);

getch();

}

void timecheck(int e1,int e2)

{

int i=1,j,m;

for(i=1;i<=e1;i++)

{

for(j=1;j<=e2;j++)

{

if(r[2][j]==i)

Distributed Computing 2013

8

{

v1[i]=t2[j];

{

for(m=i+1;m<=e1;m++)

{

v1[m]=v1[m-1];

}

}

}

}

for(i=1;i<=e2;i++)

{

for(j=1;j<=e1;j++)

{

if(r[1][j]==i)

{

v2[i]=t1[j];

for(m=i+1;m<=e2;m++)

{

v2[m]=v2[m-1];

}

}

}

}

}

void time()

{

int i;

for(i=1;i<=10;i++)

{

t1[i]=i;

t2[i]=i;

v1[i]=0;

v2[i]=0;

}

}

int max(int a,int b)

{

if(a>=b)

return a;

else

return b;

}

Output of Vector's Clock enter the number of events of process1:5

for process1

Distributed Computing 2013

9

enter 0 for no message passing

event 1 sends message to:3

event 2 sends message to:0

event 3 sends message to:0

event 4 sends message to:0

event 5 sends message to:0

enter the number of events of process2:4

for process2

enter 0 for no message passing

event 1 sends message to:0

event 2 sends message to:0

event 3 sends message to:0

event 4 sends message to:5

process 1 sends message to event 3 of process 2 at time stamp(1,0) The

updated time stamp is of process 2 (1,3)

process 2 sends message to event 5 of process 1 at time stamp(1,4) The

updated time stamp is of process 1 is (5,4)

for process 1 time stamps are:

event timestamp

1 (1,0)

2 (2,0)

3 (3,0)

4 (4,0)

5 (5,4)

for process 2 time stamps are:

event timestamp

1 (0,1)

2 (0,2)

3 (1,3)

4 (1,4)

Program No.3

PROBLEM: To Simulate the Distributed Mutual Exclusion in ‘Java’.

Program:

import java.lang.*;

class theLock extends PROBLEM

{

Distributed Computing 2013

10

theLock()

{

super();

}

}

class theThread extends Thread

{

theLock objLock;

theThread(theLock lock)

{

objLock = lock;

}

public void run()

{

System.out.println("Thread" + getName() + " : Started \n");

synchronized(objLock)

{

System.out.println("/**** START Critical Section ****/");

System.out.println("Thread" + getName() + "Start critical section, in

synchronized block \n");

++Mutex1.sharedData;

--Mutex1.sharedData2;

try

{

Thread.sleep(3000);

}

catch(InterruptedException e)

{

System.out.println("error"+e);

}

System.out.println("Thread" + getName() + "Shared Data:" +

Mutex1.sharedData+ "SharedData2 : "+ Mutex1.sharedData2);

System.out.println("Thread " + getName() + "End of criticalSection, leave

Synchronized block \n");

System.out.println("\n End critical section");

}

}

}

public class Mutex1

{

public final static int NUMTHREADS = 3;

public static int sharedData = 0;

public static int sharedData2 = 0;

public static void main(String args[])

{

theLock lockPROBLEM = new theLock();

theThread threads[] = new theThread[NUMTHREADS];

System.out.println("entered the test case \n");

System.out.println("create/ start the thread \n");

Distributed Computing 2013

11

for(int i=0;i<NUMTHREADS;++i)

{

threads[i] = new theThread(lockPROBLEM);

threads[i].start();

}

System.out.println("Join the threads to main thread \n");

try

{

for(int i=0;i<NUMTHREADS;++i)

{

threads[i].join();

}

}

catch(InterruptedException e)

{

System.out.println("join interrupted" +e);

}

System.out.println("test case completed \n");

System.exit(0);

}

}

Output of distributed mutual exclusion E:\>javac Mutex1.java

E:\>java Mutex1

Entered testcase

Create/start thread

Join the threads to main thread

ThreadThread-0started

***********Start Critical Section*************

ThreadThread-0:Start critical section in synchronised block

ThreadThread-1started

ThreadThread-2started

ThreadThread-0sharedData1 sharedData2:-1ThreadThread-0End of Critical section,le

ave synchronized block

*******End of Critical section*******

***********Start Critical Section*************

ThreadThread-1:Start critical section in synchronised block

ThreadThread-1sharedData2 sharedData2:-2ThreadThread-1End of Critical section,le

ave synchronized block

*******End of Critical section*******

***********Start Critical Section*************

ThreadThread-2:Start critical section in synchronised block

Distributed Computing 2013

12

Program No.4

PROBLEM: To implement a Distributed Chat Server using TCP Sockets in ‘Java’.

Program:

// CLIENT

import java.io.*;

import java.net.*;

public class SimpleClient{

public static void main(String args[]){

Socket clientSocket= null;

DataInputStream is= null;

PrintStream os= null;

DataInputStream inputLine= null;

System.out.println("======This is a client program======\n\n\n");

try

{

clientSocket= new Socket("127.0.0.1",2222);

System.out.println("Established the connection with remote server");

System.out.println("local port of client:"+clientSocket.getLocalPort());

os=new PrintStream(clientSocket.getOutputStream());

is=new DataInputStream(clientSocket.getInputStream());

System.out.println("enter the message to be sent to the client");

inputLine=new DataInputStream(new BufferedInputStream(System.in));

}

catch(UnknownHostException e){

System.err.println("don't know about host");

}

catch(IOException e)

{

System.err.println("Couldn't get I/O for the connection to host");

}

if(clientSocket!=null && os!=null && is!=null){

try{

String responseLine;

os.println(inputLine.readLine());

System.out.println("Message sent to remote server");

System.out.println("Waiting for reply from remote server");

while((responseLine=is.readLine())!=null)

{

if(responseLine.startsWith("BYE"))

break;

System.out.println("received reply from server: " +responseLine);

os.println(inputLine.readLine());

}

System.out.println("closing all the connections............");

Distributed Computing 2013

13

os.close();

is.close();

clientSocket.close();

}

catch(UnknownHostException e){

System.err.println("trying to connect to unknown host" +e);

}

catch(IOException e){

System.err.println("IOException: "+e);

}

}

}

}

//SERVER

import java.io.*;

import java.net.*;

public class SimpleServer {

public static void main(String args[])

{

ServerSocket echoServer = null;

String line;

DataInputStream is;

PrintStream os;

Socket clientSocket = null;

System.out.println("Welcome to Myserver");

try {

echoServer= new ServerSocket(2222,1);

System.out.println("Server socket created on port 2222");

}

catch(IOException e)

{ System.out.println(e);

}

try {

System.out.println("Waiting for Client to connect");

clientSocket= echoServer.accept();

System.out.println("Client Connection established on port" + clientSocket.getPort());

System.out.println("Client IP address:" + clientSocket.getInetAddress());

System.out.println("Client socket at Server port"+ clientSocket.getLocalPort());

is= new DataInputStream(clientSocket.getInputStream());

os= new PrintStream(clientSocket.getOutputStream());

while(true)

{

System.out.println("Wating for client to send a message") ;

line= is.readLine();

if(line.startsWith("quit"))

break;

os.println("Hello from Server"+line);

System.out.println("sent back the message;"+line);

}

Distributed Computing 2013

14

os. println ("bye");

System.out.println("Bye");

System.out.println("closing all the connections");

is.close();

os.close();

clientSocket.close();

}

catch(IOException e)

{ System.out.println(e); }

}

}

Output E:\java\ds\TCP>javac TCPSimpleClient.java

E:\java\ds\TCP>java TCPSimpleClient

E:\java\ds\TCP>java TCPSimpleClient

From server Hello

E:\java\ds\TCP>javac TCPSimpleServer.java

E:\java\ds\TCP>java TCPSimpleServer

Received Hello from/127.0.0.1

Program No.5

PROBLEM: To implement a Distributed Chat Server using UDP Sockets in ‘Java’.

Program:

//CLIENT

import java.net.*;

import java.io.*;

public class UDPSimpleClient

{

public static void main(String args[])

{

try

{

DatagramSocket socket;

DatagramPacket packet;

InetAddress address;

socket =new DatagramSocket();

address=InetAddress.getByName("127.0.0.1");

int port=2000;

String mess="Hello";

byte message[]=mess.getBytes();

packet=new DatagramPacket(message,message.length,address,port);

socket.send(packet);

socket.receive(packet);

String recmessage=new String(message);

System.out.println("from server:"+recmessage);

socket.close();

}

Distributed Computing 2013

15

catch(IOException io)

{

System.out.println("exception:"+io.getMessage());

}

}

}

//SERVER

import java.net.*;

import java.io.*;

public class UDPSimpleServer

{

public static void main(String args[])

{

DatagramSocket socket;

try

{

byte[] buffer=new byte[15];

int port=2000;

try

{

socket =new DatagramSocket(port);

while(true)

{

try

{

DatagramPacket packet=new DatagramPacket(buffer,buffer.length);

socket.receive(packet);

InetAddress client=packet.getAddress();

int client_port=packet.getPort();

System.out.println("received:"+ new String(buffer)+"from"+client);

socket.send(packet);

}

catch(UnknownHostException ue)

{

System.out.println("unknown host exception thrown");

}

}

}

catch(java.net.BindException b)

{

System.out.println("bind exception thrown");

}

}

catch(IOException e)

{

System.err.println(e);

}

}

}

Distributed Computing 2013

16

OUTPUT:

E:\java\ds\UDP>javac UDPSimpleClient.java

E:\java\ds\UDP>java UDPSimpleClient

E:\java\ds\UDP>java UDPSimpleClient

From serverHello

E:\java\ds\UDP>javac UDPSimpleServer.java

E:\java\ds\UDP>java UDPSimpleServer

ReceivedHello from/127.0.0.1

Program No.6

PROBLEM: To implement ‘Java RMI’ mechanism for accessing methods of remote systems.

Theory:

RMI applications are often comprised of two separate programs: a server and client to invoke the events

and some of PROBLEM make reference to them accessible and wait for client to invoke methods on

these PROBLEMs.

A typical application gets remote reference to one or more remote PROBLEMs in the server and the

client and pass information back and forth.

Distributed Remote PROBLEMs

1. Locate remote PROBLEMs

2. Communicate with remote PROBLEM

RMI = RPC + PROBLEM Orientation

Program: import java.rmi.*;

public class AddClient

{

public static void main(String[] args)

{

try

{

String addServerURL="rmi";//"+args[0]+"/AddServer";

AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(addServerURL);

Double d1=Double.parseDouble(args[1]);

Double d2=Double.parseDouble(args[2]);

System.out.println("The Sum is" +addServerIntf.add(d1,d2));

}

catch(Exception e)

{

System.out.println("Error");

}

}

}

Distributed Computing 2013

17

import java.net.*;

import java.rmi.*;

public class AddServer

{

public static void main(String[] args)

{

try

{

AddServerImpl addServerImpl=new AddServerImpl();

Naming.rebind("Addserver",addServerImpl);

}

catch(Exception e)

{

System.out.println("error");

}

}

}

import java.rmi.*;

public interface AddServerIntf extends Remote

{

double add(double d1,double d2) throws RemoteException;

}

import java.rmi.*;

import java.rmi.server.*;

public class AddServerImpl extends UnicastRemotePROBLEM implements AddServerIntf

{

public AddServerImpl() throws RemoteException

{

}

public double add(double d1,double d2) throws RemoteException

{

return d1+d2;

}

}

OUTPUT

E:\java\ds\rmi>javac *.java

E:\java\ds\rmi>rmic AddServerImpl

E:\java\ds\rmi>start rmiregistry

E:\java\ds\rmi>java AddServer

E:\java\ds\rmi>java AddClient 10.202.244.14 25.5 10.5

The sum is:36.0

Program No.7

PROBLEM: Modeling a taskbar server using producer consumer in ‘Java’.

Program:

Distributed Computing 2013

18

class Q

{

int n;

boolean valueSet=false;

synchronized int get()

{

if(!valueSet)

try

{

Thread.sleep(1000);

wait();

}

catch(InterruptedException e)

{

System.out.println("InterruptedException Caught");

}

System.out.println(" Got " +n);

valueSet=false;

notify();

return n;

}

synchronized void put(int n)

{

if(valueSet)

try

{

Thread.sleep(1000);

wait();

}

catch(InterruptedException e)

{

System.out.println("Interrupted Exception Caught");

}

this.n=n;

valueSet=true;

System.out.println("Put : "+n);

notify();

}

}

class Producer implements Runnable

{

Q q;

Producer(Q q)

{

this.q=q;

new Thread(this,"Producer").start();

}

public void run()

{

Distributed Computing 2013

19

int i=0;

while(true)

{

q.put(i++);

}

}

}

class Consumer implements Runnable

{

Q q;

Consumer (Q q)

{

this.q=q;

new Thread(this,"Consumer").start();

}

public void run()

{

while(true)

{

q.get();

}

}

}

class Taskbag

{

public static void main(String args[])

{

Q q= new Q();

new Producer(q);

new Consumer(q);

System.out.println("press Control-c to stop");

}

}

OUTPUT C:\Documents and Settings\geit>e:

E:\>cd vikas

E:\vikas>javac TaskBag.java

E:\vikas>java TaskBag

press ctrl + c to stop

Put :0

Got :0

Put :1

Program No.8

PROBLEM: To implement concurrent echo client-server application.

Program:

Distributed Computing 2013

20

Client.c

#include <stdio.h> /* for printf() and fprintf() */

#include <sys/socket.h> /* for socket(), connect(), send(), and recv() */

#include <arpa/inet.h> /* for sockaddr_in and inet_addr() */

#include <stdlib.h> /* for atoi() and exit() */

#include <string.h> /* for memset() */

#include <unistd.h> /* for close() */

#define RCVBUFSIZE 32 /* Size of receive buffer */

void DieWithError(char *errorMessage); /* Error handling function */

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

{

int sock; /* Socket descriptor */

struct sockaddr_in echoServAddr; /* Echo server address */

unsigned short echoServPort; /* Echo server port */

char *servIP; /* Server IP address (dotted quad) */

char *echoString; /* String to send to echo server */

char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */

unsigned Int echoStringLen; /* Length of string to echo */

int bytesRcvd, totalBytesRcvd; /* Bytes read in single recv()

and total bytes read */

if ((argc < 3) || (argc > 4)) /* Test for correct number of arguments */

{

fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n",

argv[0]);

exit(1);

}

servIP = argv[1]; /* First arg: server IP address (dotted quad) */

echoString = argv[2]; /* Second arg: string to echo */

if (argc == 4)

echoServPort = atoi(argv[3]); /* Use given port, if any */

else

echoServPort = 7; /* 7 is the well-known port for the echo service */

/* Create a reliable, stream socket using TCP */

if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)

DieWithError("socket() failed");

/* Construct the server address structure */

memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */

echoServAddr.sin_family = AF_INET; /* Internet address family */

echoServAddr.sin_addr.s_addr = inet_addr(servIP); /* Server IP address */

echoServAddr.sin_port = htons(echoServPort); /* Server port */

/* Establish the connection to the echo server */

if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)

DieWithError("connect() failed");

echoStringLen = strlen(echoString); /* Determine input length */

/* Send the string to the server */

if (send(sock, echoString, echoStringLen, 0) != echoStringLen)

DieWithError("send() sent a different number of bytes than expected");

/* Receive the same string back from the server */

totalBytesRcvd = 0;

printf("Received: "); /* Setup to print the echoed string */

Distributed Computing 2013

21

while (totalBytesRcvd < echoStringLen)

{

/* Receive up to the buffer size (minus 1 to leave space for

a null terminator) bytes from the sender */

if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)

DieWithError("recv() failed or connection closed prematurely");

totalBytesRcvd += bytesRcvd; /* Keep tally of total bytes */

echoBuffer[bytesRcvd] = '\0'; /* Terminate the string! */

printf(echoBuffer); /* Print the echo buffer */

}

printf("\n"); /* Print a final linefeed */

close(sock);

exit(0);

}

void DieWithError(char *errorMessage)

{

perror(errorMessage);

exit(1);

}

Server.c

#include <stdio.h> /* for printf() and fprintf() */

#include <sys/socket.h> /* for socket(), bind(), and connect() */

#include <arpa/inet.h> /* for sockaddr_in and inet_ntoa() */

#include <stdlib.h> /* for atoi() and exit() */

#include <string.h> /* for memset() */

#include <unistd.h> /* for close() */

#define MAXPENDING 5 /* Maximum outstanding connection requests */

#define RCVBUFSIZE 32 /* Size of receive buffer */

void DieWithError(char *errorMessage); /* Error handling function */

void HandleTCPClient(int clntSocket); /* TCP client handling function */

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

{

int servSock; /* Socket descriptor for server */

int clntSock; /* Socket descriptor for client */

struct sockaddr_in echoServAddr; /* Local address */

struct sockaddr_in echoClntAddr; /* Client address */

unsigned short echoServPort; /* Server port */

unsigned int clntLen; /* Length of client address data structure */

if (argc != 2) /* Test for correct number of arguments */

{

fprintf(stderr, "Usage: %s <Server Port>\n", argv[0]);

exit(1);

}

echoServPort = atoi(argv[1]); /* First arg: local port */

/* Create socket for incoming connections */

if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)

DieWithError("socket() failed");

Distributed Computing 2013

22

/* Construct local address structure */

memset(&echoServAddr, 0, sizeof(echoServAddr)); /* Zero out structure */

echoServAddr.sin_family = AF_INET; /* Internet address family */

echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */

echoServAddr.sin_port = htons(echoServPort); /* Local port */

/* Bind to the local address */

if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)

DieWithError("bind() failed");

/* Mark the socket so it will listen for incoming connections */

if (listen(servSock, MAXPENDING) < 0)

DieWithError("listen() failed");

for (;;) /* Run forever */

{

/* Set the size of the in-out parameter */

clntLen = sizeof(echoClntAddr);

/* Wait for a client to connect */

if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr,

&clntLen)) < 0)

DieWithError("accept() failed");

/* clntSock is connected to a client! */

printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));

//fork this process into a child and parent

processid = fork();

if (processid == 0){

/*Child Process*/

close(servSock);

HandleTCPClient(clntSock);

}

close(clntSock);

}

}

void DieWithError(char *errorMessage)

{

perror(errorMessage);

exit(1);

}

void DieWithError(char *errorMessage); /* Error handling function */

void HandleTCPClient(int clntSocket)

{

char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */

int recvMsgSize; /* Size of received message */

while(1)

{

/* Receive message from client */

if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)

DieWithError("recv() failed");

/* Send received string and receive again until end of transmission */

while (recvMsgSize > 0) /* zero indicates end of transmission */

{

/* Echo message back to client */

Distributed Computing 2013

23

if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)

DieWithError("send() failed");

/* See if there is more data to receive */

if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)

DieWithError("recv() failed");

}

}

close(clntSocket); /* Close client socket */}

Program No.9

PROBLEM: To implement the persistence storage of PROBLEMs in ‘Java’.

Program:

import java.io.*;

public class Serialization

{

public static void main(String[] args)

{

try

{

PerObj PROBLEM1=new PerObj("Hello",-7,2.7e10);

System.out.println("Created PROBLEM1:" + PROBLEM1);

FileOutputStream fos=new FileOutputStream("serial");

PROBLEMOutputStream oos=new PROBLEMOutputStream(fos);

oos.writePROBLEM(PROBLEM1);

System.out.println("Saved PROBLEM to file:"+PROBLEM1);

oos.flush();

oos.close();

}

catch(Exception e)

{

System.out.println("Exception during serialization"+e);

System.exit(0);

}

try

{

PerObj PROBLEM2;

FileInputStream fis=new FileInputStream("serial");

PROBLEMInputStream ois=new PROBLEMInputStream(fis);

PROBLEM2=(PerObj)ois.readPROBLEM();

ois.close();

System.out.println("restored PROBLEM from file:"+PROBLEM2);

}

catch(Exception e)

{

System.out.println("Exception during deserialization:"+e);

System.exit(0);

}

}

Distributed Computing 2013

24

}

class PerObj implements Serializable

{

String s;

int i;

double d;

public PerObj(String s,int i, double d)

{

this.s=s;

this.i=i;

this.d=d;

}

@Override

public String toString()

{

return "s="+s+"; i="+i+"; d="+d;

}

}

OUTPUT

E:\java\ds>java Serialization

Created PROBLEM1:s=Hello; i=-7; d=2.7E10

Saved PROBLEM to file:s=Hello; i=-7; d=2.7E10

restored PROBLEM from file:s=Hello; i=-7; d=2.7E10

Program No.10

PROBLEM: To implement multicasting using multicast sender and multicast sniffer in ‘Java’.

Program: import java.io.IOException;

import java.net.*;

public class MulticastSender

{

public static void main(String[] args)

{

InetAddress ia=null;

int port=0;

String characters="This ia multicast data\n";

byte[] data=new byte[characters.length()];

try

{

try

{

ia=InetAddress.getByName(args[0]);

}catch(UnknownHostException e)

{

System.out.println("UnknownHostException Caught");

Distributed Computing 2013

25

}

port=Integer.parseInt(args[1]);

}catch(Exception e)

{

System.err.println(e);

System.err.println("Usage:java MulticastSender MulticastAddress port");

System.exit(1);

}

characters.getBytes(0,characters.length(),data,0);

DatagramPacket dp=new DatagramPacket(data,data.length,ia,port);

try

{

MulticastSocket ms=new MulticastSocket();

ms.joinGroup(ia);

for(int i=1;i<10;i++)

{

ms.send(dp,(byte)1);

}

ms.leaveGroup(ia);

ms.close();

}

catch(SocketException se)

{

System.err.println(se);

}

catch(IOException ie)

{

System.err.println(ie);

}

}

}

import java.io.IOException;

import java.net.*;

public class MulticastSniffer

{

public static void main(String[] args)

{

InetAddress ia=null;

byte[]buffer=new byte[65509];

DatagramPacket dp=new

DatagramPacket(buffer,buffer.length);

int port=0;

try

{

try

{

ia=InetAddress.getByName(args[0]);

}

catch(UnknownHostException e){

Distributed Computing 2013

26

}

port=Integer.parseInt(args[1]);

}

catch(Exception e)

{

System.err.println(e);

System.err.println("Usage:java MulticastSniffer MulticastAddress port");

System.exit(1);

}

try

{

MulticastSocket ms=new MulticastSocket(port);

ms.joinGroup(ia);

while(true)

{

ms.receive(dp);

String s=new String(dp.getData(),0,0,dp.getLength());

System.out.println(s);

}

}

catch(SocketException se)

{

System.err.println(se);

}

catch(IOException ie)

{

System.err.println(ie);

}

}

}

OUTPUT

E:\javac MulticastSender.java

E:\java MulticastSender 224.1.1.1 2000

E:\javac MulticastSniffer.java

E:\java MulticastSnifferr 224.1.1.1 2000

this is a multicast data

this is a multicast data

this is a multicast data

this is a multicast data

E:\javac MulticastSniffer.java

E:\java MulticastSnifferr 224.1.1.1 2000

this is a multicast data

this is a multicast data

this is a multicast data

this is a multicast data