0% found this document useful (0 votes)
2K views

Distributed System Lab Manual NCS751 1

The document outlines 9 experiments related to distributed systems programming including implementing a concurrent client-server application using TCP, simulating Lamport's logical clock and distributed mutual exclusion, implementing a distributed chat server using TCP sockets, and simulating a balanced sliding window protocol and CORBA. It provides background on distributed systems concepts, descriptions of the experiments, and serves as a guide for students to complete the distributed systems laboratory assignments.

Uploaded by

Radharaman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2K views

Distributed System Lab Manual NCS751 1

The document outlines 9 experiments related to distributed systems programming including implementing a concurrent client-server application using TCP, simulating Lamport's logical clock and distributed mutual exclusion, implementing a distributed chat server using TCP sockets, and simulating a balanced sliding window protocol and CORBA. It provides background on distributed systems concepts, descriptions of the experiments, and serves as a guide for students to complete the distributed systems laboratory assignments.

Uploaded by

Radharaman
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

LABORATORY MANUAL

DISTRIBUTED SYSTEM LAB FILE (NCS 751)

Department of Computer Science and Engineering


Department of Computer Science & Engineering

LIST OF EXPERIMENTS

Expt. Title of experiment Corresponding


No. CO
1. Implement concurrent day-time client-server application. C 406.1

2. C 406.1
Configure following options on server socket and tests them:
SO_KEEPALIVE, SO_LINGER, SO_SNDBUF,
SO_RCVBUF, TCP_NODELAY
3. SO_KEEPALIVE, SO_LINGER, SO_SNDBUF, C 406.2
Simulate the functioning
SO_RCVBUF, of Lamport‟s Logical Clock in C.
TCP_NODELAY
4. C 406.2
Simulate the Distributed Mutual Exclusion in C.

5. C 406.3
Implement a Distributed Chat Server using TCP Sockets in
C.
6. C 406.3
Implement Java RMI‟ mechanism for accessing methods of
remote systems.

7. C 406.4
Simulate Balanced Sliding Window Protocol in C.
8. C 406.5
Implement CORBA mechanism by using C++program at one
end and Java program
on the other.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 2
Department of Computer Science & Engineering

Content Beyond Syllabus

9. Incrementing a counter in shared memory. C 406.1

10. Monitor SOAP request and response packets. Analyze parts C 406.2
of it and compare them with the operations (java functions)
headers.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 3
Department of Computer Science & Engineering

INTRODUCTION

In computer science, distributed computing is a field that studies distributed systems


A distributed system is a system whose components are located on different networked
computers, which communicate and coordinate their actions by passing messages to one
another. The components interact with one another in order to achieve a common goal. Three
significant characteristics of distributed systems are: concurrency of components, lack of a
global clock, and independent failure of components.

A computer program that runs within a distributed system is called a distributed program (and
distributed programming is the process of writing such programs). There are many different
types of implementations for the message passing mechanism, including pure HTTP, RPC-
like connectors and message queues.

Lamport's logical clock in distributed systems. In a distributed system, it is not possible in practice to
synchronize time across entities (typically thought of as processes) within the system; hence, the
entities can use the concept of a logical clock based on the events through which they communicate.
Concurrent access of processes to a shared resource or data is executed in mutually exclusive manner In
a distributed system, shared variables (semaphores) or a local kernel cannot be used to
implement mutual exclusion. Message passing is the sole means for implementing distributed mutual
exclusion.

TCP is a connection-oriented protocol that provides a reliable. flow of data between two
computers. Example applications that. use such services are HTTP, FTP, and Telnet.
A sliding window protocol is a feature of packet-based data transmission protocols. Sliding
window protocols are used where reliable in-order delivery of packets is required, such as in
the Data Link Layer (OSI layer 2) as well as in the Transmission Control Protocol (TCP).
Conceptually, each portion of the transmission (packets in most data link layers, but bytes in
TCP) is assigned a unique consecutive sequence number, and the receiver uses the numbers to
place received packets in the correct order, discarding duplicate packets and identifying
missing ones. The problem with this is that there is no limit on the size of the sequence number
that can be required.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 4
Department of Computer Science & Engineering

CORBA is essentially a design specification for an Object Request Broker (ORB), where an
ORB provides the mechanism required for distributed objects to communicate with one another,
whether locally or on remote devices, written in different languages.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 5
Department of Computer Science & Engineering

PREFACE

In order to efficient distributed computing, it is essential that student must have knowledge of
distributed network. The purpose of this laboratory manual is to introduce
undergraduate students about a computer program that runs within a distributed system
called a distributed program (and distributed programming is the process of writing such
programs). The manual serves as a guide for learning and implementing for the message
passing mechanism, including pure HTTP, RPC-like connectors and message queues It
basically focuses on functioning of Lamport’s Logical Clock and Distributed Mutual
Exclusion, simulate Balanced Sliding Window Protocol and CORBA mechanism. The manual
contains procedures, and pre-experiment questions to help students prepare for experiments.

This practical manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects. Though all the efforts
have been made to make this manual error free, yet some errors might have crept in
inadvertently. Suggestions from the readers for the improvement of the manual are most
welcomed.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 6
Department of Computer Science & Engineering

DO’S AND DONT’S

DO’s

1. Conform to the academic discipline of the department.


2. Enter your credentials in the laboratory attendance register.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
4. Ensure the uniqueness with respect to the methodology adopted for carrying out the
experiments.
5. Shut down the machine once you are done using it.

DONT’S

1. Eatables are not allowed in the laboratory.


2. Usage of mobile phones is strictly prohibited.
3. Do not open the system unit casing.
4. Do not remove anything from the computer laboratory without permission.
5. Do not touch, connect or disconnect any plug or cable without your faculty/laboratory
technician’s permission.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 7
Department of Computer Science & Engineering

GENERAL SAFETY INSTRUCTIONS

1. Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.

2. Report fire or accidents to your faculty /laboratory technician immediately.

3. Report any broken plugs or exposed electrical wires to your faculty/laboratory


technician immediately.

4. Do not plug in external devices without scanning them for computer viruses.

Distributed System Lab (NCS 751) Manual (CS, VII SEM)


Page 8
DISTRIBUTED SYSTEM LAB FILE (NCS 751)

Name

Roll No.

Section- Batch

Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 16
Department of Computer Science & Engineering

INDEX
Experiment Experiment Date of Date of Faculty
No. Name Conduction Submission Signature

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 15
Department of Computer Science & Engineering

EXPERIMENT - 1

Aim: Implement concurrent day-time client-server application.


Description:
TCP is a connection-oriented protocol that provides a reliable. flow of data between two
computers.
Example applications that use such services are HTTP, FTP, and Telnet.

Algorithm:
Server side programming Algorithm
STEP 1: Start the program.
STEP 2: Declare the variables and structure for the socket..
STEP 3: The socket is binded at the specified port.
STEP 4: Using the object the port and address are declared.
STEP 5: The listen and accept functions are executed.
STEP 6: If the binding is successful it waits for client request.
STEP 7: Execute the client program.

CLIENT DAY TIME ALGORITHM


STEP 1: Start the program.
STEP 2: Declare the variables and structure.
STEP 3: Socket us created and connect function is executed.
STEP 4: If the connection is successful then server sends the message.
STEP 5: The date and time is printed at the client side.
STEP 6: Stop the program.

.
Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 16
Department of Computer Science & Engineering

Pre-Experiment Questions:

Q1. What are UNIX commands?

Q2. What is Clint and sever TCP?

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 17
Department of Computer Science & Engineering

EXPERIMENT - 2

Aim: Configure following options on server socket and tests them.


SO_KEEPALIVE, SO_LINGER, SO_SNDBUF, SO_RCVBUF, TCP_NODELAY

Description:
Th is important with TCP because the connected socket is not returned to a server by accept until
the three-way handshake is completed by the TCP layer. To ensure that one of these socket
options is set for the connected socket when the three-way handshake completes, we must set
that option for the listening socket.
There are various ways to get and set the options that affect a socket:

• The getsockopt and setsockopt functions.


• The fcntl function, which is the POSIX way to set a socket for nonblocking I/O, signal-
driven I/O, and to set the owner of a socket.
• The ioctl function.

Pre-Experiment Questions:

Q1. Why socket options required?

Q2. What is socket programming.

Procedure:

Write a server(TCP) C Program that sets the socket options using stockpot on server one by one
and displays the information using getsockopt.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 18
Department of Computer Science & Engineering

Program:

Server program:

#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";

// Creating socket file descriptor


if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}

// Forcefully attaching socket to the port 8080


if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );

// Forcefully attaching socket to the port 8080


if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 19
Department of Computer Science & Engineering

exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&address,

(socklen_t*)&addrlen))<0) }

perror("accept");
exit(EXIT_FAILURE);
}
valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , hello , strlen(hello) , 0 );
printf("Hello message sent\n");
return 0;
}
Cient program:

#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080

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


{
struct sockaddr_in address;
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}

memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 20
Department of Computer Science & Engineering

// Convert IPv4 and IPv6 addresses from text to binary form


if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)

{
printf("\nInvalid address/ Address not supported \n");
return -1;
}

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


{
printf("\nConnection Failed \n");
return -1;
}

send(sock , hello , strlen(hello) , 0 );


printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n",buffer );
return 0;
}

Post-Experiment Questions:

Q1. Exchanging one hello message between server and client to demonstrate the
client/server model.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 21
Department of Computer Science & Engineering

EXPERIMENT - 3

Aim: Simulate the functioning of Lamport‟s Logical Clock in C

Descriptions:
The algorithm of Lamport timestamps is a simple algorithm used to determine the order of events
in a distributed computer system. As different nodes or processes will typically not be perfectly
synchronized, this algorithm is used to provide a partial ordering of events with minimal
overhead, and conceptually provide a starting point for the more advanced vector clock method.
They are named after their creator, Leslie Lamport.
Distributed algorithms such as resource synchronization often depend on some method of
ordering events to function. For example, consider a system with two processes and a disk. The
processes send messages to each other, and also send messages to the disk requesting access. The
disk grants access in the order the messages were sent. For example process {\displaystyle
A} sends a message to the disk requesting write access, and then sends a read instruction message
to process {\display style B}Process {\display style B} receives the message, and as a result
sends its own read request message to the disk. If there is a timing delay causing the disk to
receive both messages at the same time, it can determine which message happened-before the
other: {\display style A} happens-before {\displaystyle B} if one can get from {\displaystyle
A} to {\display style B} by a sequence of moves of two types: moving forward while remaining
in the same process, and following a message from its sending to its reception. A logical clock
algorithm provides a mechanism to determine facts about the order of such events.

Pre-Experiment Questions:
Q1. Explain Time stamp.

Q2.What is Lamport timestamps ?

Algorithms:

1. A process increments its counter before each event in that process,When a process sends a
message, it includes its counter value with the message;
2. On receiving a message, the counter of the recipient is updated, if necessary, to the greater
of its current counter and the timestamp in the received message.
3. The counter is then incremented by 1 before the message is considered received.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 22
Department of Computer Science & Engineering

Program:

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
#include<stdlib.h>
#include<graphics.h>
#include<string.h>
#include<dos.h>

void main(){
int s[4][9],n,m=0;
int i,j,next=0,step=0;
int msg[10][4]={0},totmsg;
char op;
int pi,pj,ei,ej;
clrscr();
cout<<“\nProgram for Lamport Logical Clock”;
cout<<“\nEnter Number Of Process “;
cin>>n;
for(i=0;i<n;i++){
cout<<“\nEnter number of STATES of process P”<<i<<” “;
cin>>s[i][8];
for(j=1;j<=s[i][8];j++){
s[i][j]=j;
}
}
do{
cout<<“\nEnter message transit”;
cout<<“\nFROM ->\nEnter Process Number P”;
cin>>msg[m][0];
cout<<“\nEnter Event Number e”;
cin>>msg[m][1];
cout<<“\nTO ->\nEnter Process Number P”;
cin>>msg[m][2];
cout<<“\nEnter Event Number e”;

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 23
Department of Computer Science & Engineering

cin>>msg[m][3];
cout<<“\n\nPress ‘y’ to continue”;
op=getch();
cout<<op;
m++;
totmsg=m;
}while(op==’y’);
m=0;
for (i=0;i<totmsg;i++){
pi=msg[i][0];
ei=msg[i][1];
pj=msg[i][2];
ej=msg[i][3];
if(s[pj][ej]< (s[pi][ei]+1)){
s[pj][ej]=s[pi][ei]+1;

for (j=ej+1;j<=s[pj][8];j++){
s[pj][j]=s[pj][j-1]+1;
}

}
}
int gd=DETECT,gm;
initgraph(&gd,&gm,”C:\\TC\\BGI”);
outtextxy(200,15,”Program For Lamport Logical Clock”);
//drawing process and events
for(i=0;i<n;i++){
char* p1;
itoa(i,p1,10);
outtextxy(5,100+next,”P”);
outtextxy(13,100+next,p1);
line(100,100+next,600,100+next);
for(j=1;j<=s[i][8];j++){
char* p2;
itoa(j,p2,10);

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 24
Department of Computer Science & Engineering

outtextxy(100+step,90+next,”e”);
outtextxy(110+step,90+next,p2);
//timestamp
char* p3;
itoa(s[i][j]-1,p3,10);
outtextxy(100+step,110+next,”t”);
outtextxy(110+step,110+next,p3);
circle(105+step,100+next,5);
step+=50;
}
step=0;
next+=100;
}
delay(2000);
//drawing message transit
for(m=0;m<totmsg;m++){
setlinestyle(SOLID_LINE,1,3);
setcolor(m+4);
line(msg[m][1]*50+50,msg[m][0]*100+100,msg[m][3]*50+50,msg[m][2]*100+100);
if (msg[m][2]>msg[m][0]){
line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+50,msg[m][2]*100+90);
line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+40,msg[m][2]*100+90);
}

else{

line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+50,msg[m][2]*100+110);

line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+40,msg[m][2]*100+110);
}
}
getch();
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 25
Department of Computer Science & Engineering

Post experiment questions:

Q1. What are the types of transparencies?


Q2. Define transparencies.
Q3. Define System model.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 26
Department of Computer Science & Engineering

EXPERIMENT 4

Aim: Simulate the Distributed Mutual Exclusion in C


Descriptions: Mutual exclusion: Concurrent access of processes to a shared resource or data is
executed in mutually exclusive manner.
Only one process is allowed to execute the critical section (CS) at any given time.
In a distributed system, shared variables (semaphores) or a local kernel cannot be used to
implement mutual exclusion.
Message passing is the sole means for implementing distributed mutual exclusion.
Distributed mutual exclusion algorithms must deal with unpredictable message delays and
incomplete knowledge of the system state.
Three basic approaches for distributed mutual exclusion:
1) Token based approach
2) Non-token based approach
3 )Quorum based approach Token-based approach
A unique token is shared among the sites.
A site is allowed to enter its CS if it possesses the token.
Non-token based approach Two or more successive rounds of messages are exchanged among
the sites to determine which site will enter the CS next.
Quorum based approach: Each site requests permission to execute the CS from a subset of sites
(called a quorum). Any two quorums contain a common site. This common site is responsible to
make sure that only one request executes the CS at any time.

Pre-Experiment Question:

Q1. What is Mutual exclusion?

Q2. What is distributed mutual exclusion?

Algorithms :

1. Pushing its request in its own queue (ordered by time stamps)


2. Sending a request to every node.
3. Waiting for replies from all other nodes.
4. If own request is at the head of its queue and all replies have been received, enter critical
section.
5. Upon exiting the critical section, remove its request from the queue and send a release
message to every process.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 27
Department of Computer Science & Engineering
Program:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
int rc1, rc2;
pthread_t thread1, thread2;
/* Create independent threads each of which will execute functionC */
if( (rc1=pthread_create( &thread1, NULL, &functionC, NULL)) )
{
printf("Thread creation failed: %d\n", rc1);
}
if( (rc2=pthread_create( &thread2, NULL, &functionC, NULL)) )
{
printf("Thread creation failed: %d\n", rc2);
}
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
exit(0);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\n",counter);
pthread_mutex_unlock( &mutex1 );
}
Compile: cc -lpthread mutex1.c Run: ./a.out Results:
Counter value: 1 Counter value: 2
join1.c
#include <stdio.h>
#include <pthread.h>
#define NTHREADS 10
void *thread_function(void *);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 28
Department of Computer Science & Engineering

pthread_t thread_id[NTHREADS];
int i, j;
for(i=0; i < NTHREADS; i++)
{
pthread_create( &thread_id[i], NULL, thread_function, NULL );}

for(j=0; j < NTHREADS; j++)


{
pthread_join( thread_id[j], NULL);
}
/* Now that all threads are complete I can print the final result. */
/* Without the join I could be printing a value before all the threads */
/* have been completed.*/
printf("Final counter value: %d\n", counter);
}
void *thread_function(void *dummyPtr)
{
printf("Thread number %ld\n", pthread_self());
pthread_mutex_lock( &mutex1 );
counter++;
pthread_mutex_unlock( &mutex1 );
}
Compile:cc-lpthreadjoin1.c Run:./a.out Results:
Thread number 1026
Thread number 2051
Thread number 3076
Thread number 4101
Thread number 5126
Thread number 6151

Thread number 7176


Thread number 8201
Thread number 9226
Thread number 10251
Final counter value: 10
cond1.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 29
Department of Computer Science & Engineering

void *functionCount1();
void *functionCount2();
int count = 0;#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, NULL, &functionCount1, NULL);
pthread_create( &thread2, NULL, &functionCount2, NULL);
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Final count: %d\n",count);
exit(0);}

// Write numbers 1-3 and 8-10 as permitted by functionCount2()


void *functionCount1()
{
for(;;)
{
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
// Wait while functionCount2() operates on count
// mutex unlocked if condition varialbe in functionCount2() signaled.
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
// Write numbers 4-7
void *functionCount2()
{

for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < COUNT_HALT1 || count > COUNT_HALT2 )
{
// Condition of if statement has been met.
// Signal to free waiting thread by freeing the mutex.
// Note: functionCount1() is now permitted to modify "count".

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 30
Department of Computer Science & Engineering

pthread_cond_signal( &condition_var );
}
else
{

count++;
printf("Counter value functionCount2: %d\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= COUNT_DONE) return(NULL);
}
}
Compile: cc -lpthread cond1.c Run: ./a.out Results:
Counter value functionCount1: 1
Counter value functionCount1: 2
Counter value functionCount1: 3
Counter value functionCount2: 4
Counter value functionCount2: 5
Counter value functionCount2: 6
Counter value functionCount2: 7
Counter value functionCount1: 8
Counter value functionCount1: 9
Counter value functionCount1: 10
Final count: 10
.

Post-Experiment Questions

Q1. . Explain the various type communications.


Q2. Define Mutual Exclusion in distributed system.
Q3. Define deadlock detection in distributed system.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 31
Department of Computer Science & Engineering

EXPERIMENT – 5

Aim: Implement a Distributed Chat Server using TCP Sockets in


Descriptions:
TCP is a connection-oriented protocol that provides a reliable. flow of data between two
computers. Example applications that. use such services are HTTP, FTP, and Telnet.

Program : ►SOURCE CODE


#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define PORT 5555
#define MAXMSG 512
int
read_from_client (int filedes)
{
char buffer[MAXMSG];
int nbytes;
nbytes = read (filedes, buffer, MAXMSG);
if (nbytes < 0)
{
/* Read error. */
perror ("read");
exit (EXIT_FAILURE);
}
else if (nbytes == 0)
/* End-of-file. */
return -1;
else
{
/* Data read. */
fprintf (stderr, "Server: got message: `%s'\n", buffer);
return 0;
}
}
int
main (void)

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 32
Department of Computer Science & Engineering

{
extern int make_socket (uint16_t port);
int sock;
fd_set active_fd_set, read_fd_set;

int i;
struct sockaddr_in clientname;
size_t size;

/* Create the socket and set it up to accept connections. */


sock = make_socket (PORT);
if (listen (sock, 1) < 0)
{
perror ("listen");
exit (EXIT_FAILURE);
}
/* Initialize the set of active sockets. */
FD_ZERO (&active_fd_set);
FD_SET (sock, &active_fd_set);
while (1)
{
/* Block until input arrives on one or more active sockets. */
read_fd_set = active_fd_set;
if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0)
{
perror ("select");
exit (EXIT_FAILURE);
}
/* Service all the sockets with input pending. */
for (i = 0; i < FD_SETSIZE; ++i)
if (FD_ISSET (i, &read_fd_set))
{
if (i == sock)
{
/* Connection request on original socket. */
int new;
size = sizeof (clientname);
new = accept (sock,
(struct sockaddr *) &clientname,
&size);
if (new < 0)

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 33
Department of Computer Science & Engineering

{
perror ("accept");
exit (EXIT_FAILURE);
}
fprintf (stderr,
"Server: connect from host %s, port %hd.\n",
inet_ntoa (clientname.sin_addr),
ntohs (clientname.sin_port));
FD_SET (new, &active_fd_set);
}
else
{
/* Data arriving on an already-connected socket. */
if (read_from_client (i) < 0) {
close (i);
FD_CLR (i, &active_fd_set);
}}}}}

Department of Computer Science & Engineering

Post-Experiment Questions:

Q1. What is the use of UDP?


Q2. What are the methods provides by datagram socket?
Q3.. What are the characteristic of network hidden by stream abstraction?

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 34
Department of Computer Science & Engineering

EXPERIMENT – 6

Aim: Implement Java RMI mechanism for accessing methods of remote systems.

Descriptions:

RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in
one system (JVM) to access/invoke an object running on another JVM.

RMI is used to build distributed applications; it provides remote communication between Java
programs. It is provided in the package java.rmi.
Algorithm :

import java.rmi.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
public Hello (String msg) throws RemoteException {
message = msg;
}
public String say() throws RemoteException {
return message;
}
}
HelloClient.java
import java.rmi.Naming;
public class HelloClient
{
public static void main (String[] argv) {
try {
HelloInterface hello =(HelloInterface) Naming.lookup ("//192.168.10.201/Hello");
System.out.println (hello.say());
}
catch (Exception e){
System.out.println ("HelloClient exception: " + e);}
}
}
HelloInterface.java
import java.rmi.*;
public interface HelloInterface extends Remote {
public String say() throws RemoteException;
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 35
Department of Computer Science & Engineering

HelloServer.java
import java.rmi.Naming;
public class HelloServer}

public static void main (String[] argv)


{
try {
Naming.rebind ("Hello", new Hello ("Hello,From Roseindia.net pvt ltd!"));
System.out.println ("Server is connected and ready for operation.");
} catch (Exception e)

{
System.out.println ("Server not connected: " + e);
}
}
}

Post-Experiment Questions:
Q1. What is the use of RMI registry?
Q2. What is meant by distributed garbage collection?
Q3. Explain the use of Reflection in RMI?

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 36
Department of Computer Science & Engineering

EXPERIMENT - 7

Aim: Simulate Balanced Sliding Window Protocol in C

Descriptions:
A sliding window protocol is a feature of packet-based data transmission protocols. Sliding
window protocols are used where reliable in-order delivery of packets is required, such as in
the Data Link Layer (OSI layer 2) as well as in the Transmission Control Protocol (TCP).
Conceptually, each portion of the transmission (packets in most data link layers, but bytes in
TCP) is assigned a unique consecutive sequence number, and the receiver uses the numbers to
place received packets in the correct order, discarding duplicate packets and identifying
missing ones. The problem with this is that there is no limit on the size of the sequence number
that can be required.

Program:

#include <STDIO.H>
#include <iostream.h>
#include <string>
#define THANKS -1
void main()
{
FILE *r_File1;
FILE *w_File2;
int m_framecount;
int frameCount = 0;
long currentP = 0;
long sentChar = 0;
long recvedChar = 0;
char s_name[100];
char d_name[100];
char *sp = s_name;
char *dp = d_name;
int slidingWin;
int frameSize;
int dataSize;

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 37
Department of Computer Science & Engineering

bool isEnd = false;


struct FRAME{
int s_flag;
intsequenceNo;
char data[90]

int n_flag;
};
FRAME frame;
frame.s_flag = 126;//set start flag
frame.n_flag = 126;//set end flag
memset(frame.data, 0, 91);//use 0 to fill full the member array in structure frame.
struct ACK{

int s_flag;
int nextSeq;
int n_flag;
}ack;
//initialize start flag and end flag in structure ack.
ack.s_flag = 126;
ack.n_flag = 126;
ack.nextSeq = NULL;
//ask user to enter file name and size of sliding window.
lable1 : cout <<"Please enter source file's name!"<<endl;
cin >> sp;
cout <<"Please enter destination file's name!"<<endl;
cin >> dp;
lable2: cout <<"Please chose size of sliding window 2--7"<<endl;
cin >> slidingWin;
if((slidingWin >7 )| (slidingWin < 2))
{
cout << "wrong enter"<<endl;
goto lable2;
}
lable3: cout<< "Please enter the size of frame 14--101 Only!" << endl;
cin >>frameSize;
if((frameSize > 101) | (frameSize < 14))
{ cout << "please enter right number!"<< endl;
goto lable3;
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 38
Department of Computer Science & Engineering

//use frameSize to decide the size of data array in structor frame.


dataSize = frameSize - 12;
//dynamic generate a frame array with user enter's size of sliding window
FRAME *pf = new FRAME[slidingWin];
int seqNo = 0;
//strat loop for transmission.
while (ack.nextSeq != THANKS)

{
cout << "THE PROCESS ON SENDER SIDER..."<<endl;
//open a source file by read mode.
if((r_File1 = fopen(sp, "rb")) == NULL)

cout << "source file could not be opened please check it and re-start!" <<endl;
goto lable1;
}
else
{
cout<<"Opening a file for read...";
cout <<endl;
cout <<endl;
//after open the file, use fseek to resume the last position of a file pointer.
//Then start to read from that position.
fseek(r_File1,currentP,SEEK_SET);
//start loop for create frame array
for (int i = 0; i < slidingWin ; i++)// i is the frame array's index
{
frame.sequenceNo = seqNo;
if ((seqNo >= 7) == true)
{
seqNo = 0;//set sequencce number
}
else
{
seqNo = seqNo +1;
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 39
Department of Computer Science & Engineering

//This loop is used to fill the characters read from opened file to char array data which
//is a memeber of structure frame.
//we have to reseve a byte for \0 which is used to identify the end of the data array.
//that means each time we only read datasize -1 characters to the data array.
for (int j = 0; j < dataSize -1; j++)
{ //if it is not end of file read a character from file then save it into data
//field in frame structure.
frame.data[j]= fgetc(r_File1);
sentChar++;//calculate how many characters will be sent.*/
if (frame.data[j]
{
cout<< "There is the end of file"<<endl;
isEnd = true;
//sentChar++;
break;
}

}if (isEnd == true)


{
pf[i] = frame; //save a frame into frame array.
//frameCount = i;
frameCount++;
m_framecount = i +1;
cout <<endl;
cout << "The squence number is " << pf[i].sequenceNo <<endl;
cout << "The start flag is " << pf[i].s_flag <<endl;
cout << "The Data is---->" << pf[i].data <<endl;
cout << "The end flag is " << pf[i].n_flag <<endl;
cout << "There are " <<frameCount <<" frames has been created!"<<endl;
cout << "frame " << pf[i].sequenceNo <<" has been transported!";
cout<< endl;
fclose(r_File1);
break;
}
pf[i] = frame;//sava current frame to frame buffer.
//display some informaiton of frame buffer.
frameCount++;
m_framecount = i +1;
cout <<endl;
cout << "The squence number is " << pf[i].sequenceNo <<endl;
cout << "The start flag is " << pf[i].s_flag <<endl;
cout << "The Data is---->" << pf[i].data <<endl;
cout << "The end flag is " << pf[i].n_flag <<endl;
cout << "There are total " <<frameCount <<" frames has been created!"<<endl;

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 40
Department of Computer Science & Engineering

//cout << "frame " << pf[i].sequenceNo <<" has been transported!";
cout<< endl;
currentP = ftell(r_File1);//to record the current position of a file pointer
}
fflush(r_File1);//refresh
}

//print out some information.


cout <<endl;
cout <<"Total " << sentChar << " characters have been sent on this session!"<<endl;
cout <<endl;
cout << "waiting for ACK!" <<endl;
cout <<endl;
cout <<endl;

int nextNoRecord = 0;
cout<<"THE PROCESS ON RECEIVER SIDE..."<<endl;
//open a file for write
if((w_File2 = fopen(dp, "ab")) != NULL)
{
cout<<"opening a file for write..."<<endl;
for (int m = 0; m < m_framecount ; m++)
{
for (int n = 0; n < dataSize -1; n++)
{//check whether islast character.
if(pf[m].data[n]
{
ack.nextSeq = THANKS;
//fputc(pf[m].data[n],w_File2);
recvedChar++;
break

}
//write the character from current frame 's which in t index of data flied.
fputc(pf[m].data[n],w_File2);
recvedChar++;
}
cout << "The string ---->" << pf[m].data <<" written succeed"<<endl;
fflush(w_File2);//refresh
if(ack.nextSeq == THANKS)
{

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 41
Department of Computer Science & Engineering

fclose(w_File2);
break;
}
nextNoRecord= pf[m].sequenceNo;
}

cout <<endl;
cout <<"Total "<<recvedChar << " characters have been received on this session"<<endl;
cout <<endl;
cout << "send acknowledgement!" <<endl;
cout <<endl;
cout <<endl;
if (ack.nextSeq != THANKS)
{
cout<<"CheckACK"<<endl;
if (nextNoRecord
{
ack.nextSeq =0 ;
}
else
{
ack.nextSeq = nextNoRecord +1;
}
cout << "The next expect frame is " << ack.nextSeq <<endl;
}
else
{ cout<<"CheckACK"<<endl;
cout << "The acknowledgement is thanks. The transmission complete..."<<endl;
//delete the frame buffer array .
delete []pf;
}
}
else
{cout << "File could not be opened" << endl;}
cout <<endl;
cout <<endl;
}
/*can be used to check how many bytes in the specified fill

numRead = 0;
fseek(r_File1,0,SEEK_END);
numRead = ftell(r_File1);
cout << "There are " << numRead <<" Bytes in the file" << endl;*/
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 42
Department of Computer Science & Engineering

►OUTPUT
1: use fixed source file name and fixed destination file name and fixed sliding

window size (5) to test program.


Read file successfully.
Create frames successfully.
Save frames into frame buffer which is size 5 successfully.
Write data from frames successfully.
Returns to ACK successfully.
Re-create new frames successfully.
Search the end of source file successfully.
2: use keyboard to input the “source file name”, “destination file name”, “sliding
windows size”, and “frame size” to test program
Read file successfully.
Create frames successfully.
Save frames into frame buffer which is size 5 successfully.
Write data from frames successfully.
Returns to ACK successfully.
Re-create new frames successfully.
Search the end of source successfully.

Post-Experiment Questions:

Q1. Define sliding window protocol ‘

Q2.Explain working of a sliding window protocol .

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 43
Department of Computer Science & Engineering

EXPERIMENT - 8

Aim: Implement CORBA mechanism by using „C++‟ program at one end and „Java‟ program
on the other.

Description:
CORBA is essentially a design specification for an Object Request Broker (ORB), where an
ORB provides the mechanism required for distributed objects to communicate with one another,
whether locally or on remote devices, written in different languages, or at different locations on
a network.

Pre Experiment Questions:

Q1. Define Concurrency control.

Q2.What is meant by nested transactions?

Q3. Define strict two phase locking.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 44
Department of Computer Science & Engineering

Program:

Creating the Server


#include <iostream>
#include "OB/CORBA.h"
#include <OB/Cosnaming.h>
#include "crypt.h"
#include "cryptimpl.h"
using namespace std;
int main(int argc, char** argv)
{
// Declare ORB and servant object
CORBA::ORB_var orb;
CryptographicImpl* CrypImpl = NULL;
try {
// Initialize the ORB.
orb = CORBA::ORB_init(argc, argv);
// Get a reference to the root POA
CORBA::Object_var rootPOAObj =
orb->resolve_initial_references("RootPOA");
// Narrow it to the correct type
PortableServer::POA_var rootPOA =
PortableServer::POA::_narrow(rootPOAObj.in());
// Create POA policies
CORBA::PolicyList policies;
policies.length(1);
policies[0] =
rootPOA->create_thread_policy
(PortableServer::SINGLE_THREAD_MODEL);
// Get the POA manager object
PortableServer::POAManager_var manager = rootPOA->the_POAManager();
// Create a new POA with specified policies
PortableServer::POA_var myPOA = rootPOA->create_POA
("myPOA", manager, policies);
// Free policies
CORBA::ULong len = policies.length();
for (CORBA::ULong i = 0; i < len; i++)
policies[i]->destroy();
// Get a reference to the Naming Service root_context
CORBA::Object_var rootContextObj =
orb->resolve_initial_references("NameService");
// Narrow to the correct type
CosNaming::NamingContext_var nc =
CosNaming::NamingContext::_narrow(rootContextObj.in());
// Create a reference to the servant
CrypImpl = new CryptographicImpl(orb);

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 45
Department of Computer Science & Engineering

// Activate object
PortableServer::ObjectId_var myObjID =myPOA->activate_object(CrypImpl);
// Get a CORBA reference with the POA through the servant
CORBA::Object_var o = myPOA->servant_to_reference(CrypImpl);// The reference is
converted to a character string
CORBA::String_var s = orb->object_to_string(o);
cout << "The IOR of the object is: " << s.in() << endl;
CosNaming::Name name;
name.length(1);
name[0].id = (const char *) "CryptographicService";
name[0].kind = (const char *) "";
// Bind the object into the name service
nc->rebind(name,o);
// Activate the POA
manager->activate();
cout << "The server is ready.
Awaiting for incoming requests..." << endl;
// Start the ORB
orb->run();
} catch(const CORBA::Exception& e) {
// Handles CORBA exceptions
cerr << e << endl;
}
// Decrement reference count
if (CrypImpl)
CrypImpl->_remove_ref();
// End CORBA
if (!CORBA::is_nil(orb)){
try{
orb->destroy();
cout << "Ending CORBA..." << endl;
} catch (const CORBA::Exception& e)
{
cout << "orb->destroy() failed:" << e << endl;
return 1;
}
}
return 0;
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 46
Department of Computer Science & Engineering

Implementing the Client


#include <iostream>
#include <string>
#include "OB/CORBA.h"
#include "OB/Cosnaming.h"
#include "crypt.h"
using namespace std;

int main(int argc, char** argv)


{
// Declare ORB
CORBA::ORB_var orb;
try {
// Initialize the ORB
orb = CORBA::ORB_init(argc, argv);
// Get a reference to the Naming Service
CORBA::Object_var rootContextObj =
orb->resolve_initial_references("NameService");
CosNaming::NamingContext_var nc =
CosNaming::NamingContext::_narrow(rootContextObj.in());
CosNaming::Name name;
name.length(1);
name[0].id = (const char *) "CryptographicService";
name[0].kind = (const char *) "";
// Invoke the root context to retrieve the object reference
CORBA::Object_var managerObj = nc->resolve(name);
// Narrow the previous object to obtain the correct type
::CaesarAlgorithm_var manager =
::CaesarAlgorithm::_narrow(managerObj.in());
string info_in,exit,dummy;
CORBA::String_var info_out;
::CaesarAlgorithm::charsequence_var inseq;
unsigned long key,shift;
try{
do{
cout << "\nCryptographic service client" << endl;
cout << "----------------------------" << endl;
do{ // Get the cryptographic key
if (cin.fail())
{
cin.clear();
cin >> dummy;
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 47
Department of Computer Science & Engineering

cout << "Enter encryption key: ";


cin >> key;
} while (cin.fail());
do{ // Get the shift

if (cin.fail())
{
cin.clear();
cin >> dummy;
}
cout << "Enter a shift: ";
cin >> shift;
} while (cin.fail());
// Used for debug pourposes
//key = 9876453;
//shift = 938372;

getline(cin,dummy); // Get the text to encrypt


cout << "Enter a plain text to encrypt: ";
getline(cin,info_in);
// Invoke first remote method
inseq = manager->encrypt
(info_in.c_str(),key,shift);
cout << "------------------------------------------"
<< endl;
cout << "Encrypted text is: "
<< inseq->get_buffer() << endl;
// Invoke second remote method
info_out = manager->decrypt(inseq.in(),key,shift);
cout << "Decrypted text is: "
<< info_out.in() << endl;
cout << "-------------------------------------------"
<< endl;
cout << "Exit? (y/n): ";
cin >> exit;
} while (exit!="y");
// Shutdown server message
manager->shutdown();

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 48
Department of Computer Science & Engineering

} catch(const std::exception& std_e){


cerr << std_e.what() << endl;
}

}catch(const CORBA::Exception& e) {
// Handles CORBA exceptions
cerr << e << endl;
}
// End CORBA
if (!CORBA::is_nil(orb)){
try{
orb->destroy();
cout << "Ending CORBA..." << endl;
} catch(const CORBA::Exception& e)
{
cout << "orb->destroy failed:" << e << endl;
return 1;
}
}
return 0;
}

►OUTPUT
Running the Client-server Application Once we have implemented the client and the server,
it‟s time to connect them. Because our demonstration client and server exchange object
references via the naming service, we must ensure that the naming service (which is called
nameserv in Orbacus) is running. We use some command-line options to tell the naming
service the host and port on which it should listen. nameserv -OAhost localhost -OAport 8140
After this, we can start the server with a command-line option to tell it how to contact the
naming service. server -ORBInitRef NameService=corbaloc:iiop:localhost:8140/NameService
Finally we can start the client, again with a command-line option to tell it how to contact the
naming service. client -ORBInitRef NameService=corbaloc:iiop:localhost:8140/NameService

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 49
Department of Computer Science & Engineering

EXPERIMENT - 9

Aim: Incrementing a counter in shared memory.

Algorithm

1) Write a server C Program using Shared memory and semaphore (server increments
counter between sem_wait and sem_post). Create shared memory using mmap.
2) Write a client C Program that reads counter value between sem_wait and sem_post.
Access shared memory using open.

Consider using Atomic Integer:

public class Foo


{
private AtomicInteger counter = new AtomicInteger(0);

public void increment()


{
counter.incrementAndGet();
}

public void decrement()


{
counter.decrementAndGet();
}

public int getValue()


{
return counter.get();
}
}

using the synchronized methods:

public class Foo


{
private volatile int counter;

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 50
Department of Computer Science & Engineering

public synchronized void increment()


{
counter++;
}

public synchronized void decrement()


{
counter--;
}

public int getValue()


{
return counter;
}
}

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 51
Department of Computer Science & Engineering

EXPERIMENT – 10

Aim: Monitor SOAP request and response packets. Analyze parts of it and compare them with
the operations (java functions) headers.

Algorithm
1) Start WS-Monitor on port 4040 and forwarding port 808
2) Change the service target port from 8080 to 4040
3) WS-Monitor will capture SOAP request and SOAP response.
4) Study request and response packets and try to relate them with operation name,
service name, namespace, etc.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 52
Department of Computer Science & Engineering

APPENDIX

AKTU SYLLABUS

NCS 751: DISTRIBUTED SYSTEM LAB

The following programs may be developed preferably on ‘UNIX’ platform:

1. Simulate the functioning of Lamport’s Logical Clock in ‘C’.

2. Simulate the Distributed Mutual Exclusion in ‘C’.

3. Implement a Distributed Chat Server using TCP Sockets in ‘C’.

4. Implement RPC mechanism for a file transfer across a network in ‘C’

5. Implement ‘Java RMI’ mechanism for accessing methods of remote systems.

6. Simulate Balanced Sliding Window Protocol in ‘C’.

7. Implement CORBA mechanism by using ‘C++’ program at one end and ‘Java program on the

other.

Distributed System Lab (NCS 751) Manual (CS, VII SEM) Page 53

You might also like