Vision Missions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

Introduction to Distributed System

A distributed system is an application that executes a collection of protocols to


coordinate the actions of multiple processes on a network, such that all components
cooperate together to perform a single or small set of related tasks.
Why build a distributed system? There are lots of advantages including the ability
to connect remote users with remote resources in an open and scalable way. When
we say open, we mean each component is continually open to interaction with
other components. When we say scalable, we mean the system can easily be
altered to accommodate changes in the number of users, resources and computing
entities.
Thus, a distributed system can be much larger and more powerful given the
combined capabilities of the distributed components, than combinations of stand-
alone systems. But it’s not easy – for a distributed system to be useful, it must be
reliable. This is a difficult goal to achieve because of the complexity of the
interactions between simultaneously running components.
To be truly reliable, a distributed system must have the following characteristics:
Fault-Tolerant: It can recover from component failures without performing
incorrect actions.
● Highly Available: It can restore operations, permitting it to resume
providing services even when some components have failed.
● Recoverable: Failed components can restart themselves and re-join the
system, after the cause of failure has been repaired.
● Consistent: The system can coordinate actions by multiple components
often in the presence of concurrency and failure. This underlies the
ability of a distributed system to act like a non-distributed system.
● Scalable: It can operate correctly even as some aspect of the system is
scaled to a larger size. For example, we might increase the size of the
network on which the system is running. This increases the frequency of
network outages and could degrade a “non-scalable” system. Similarly,
we might increase the number of users or servers, or overall load on the
system. In a scalable system, this should not have a significant effect.
● Predictable Performance: The ability to provide desired responsiveness in
a timely manner.
● Secure: The system authenticates access to data and services
These are high standards, which are challenging to achieve. Probably the most
difficult challenge is a distributed system must be able to continue operating
correctly even when components fail. This issue is discussed in the following
excerpt of an interview with Ken Arnold. Ken is a research scientist at Sun and is
one of the original architects of Jinni and was a member of the architectural team
that designed CORBA.

APPLICATIONS OF DISTRIBUTED SYSTEM


There are two main reasons for using distributed systems and distributed
computing. First, the very nature of the application may require the use of a
communication network that connects several computers. For example, data is
produced in one physical location and it is needed in another location. Second,
there are many cases in which the use of a single computer would be possible in
principle, but the use of a distributed system is beneficial for practical reasons. For
example, it may be more cost-efficient to obtain the desired level of performance
by using a cluster of several low-end computers, in comparison with a single high-
end computer. A distributed system can be more reliable than a non-distributed
system, as there is no single point of failure. Moreover, a distributed system may
be easier to expand and manage than a monolithic uniprocessor system.
Examples of distributed systems and applications of distributed computing include
the following Telecommunication networks:
● Telephone networks and cellular networks.
● Computer networks such as the Internet.
● Wireless sensor networks.
● Routing algorithms.
● Network applications
● World wide web and peer-to-peer networks.
● Massively multiplayer online games and virtual reality communities.
● Distributed databases and distributed database management systems.
● Network file systems.
● Distributed information processing systems such as banking systems and
airline reservation systems. Real-time process control:
● Aircraft control systems.
● Industrial control systems.
● Parallel computation: Scientific computing, including cluster computing
and grid computing and various volunteer computing projects; see the list
of distributed computing projects.
Experiment: 1
Objective: Simulate the functioning of Lamport’s Logical Clock in ‘C’.

Source Code:

#include<stdio.h>
#include<conio.h>
int max1(int a, int b) //to find the maximum timestamp between two events
{
if (a>b)
return a;
else
return b;
}

int main()
{
int i,j,k,p1[20],p2[20],e1,e2,dep[20][20];
printf("enter the events : ");
scanf("%d %d",&e1,&e2);
for(i=0;i<e1;i++)
p1[i]=i+1;
for(i=0;i<e2;i++)
p2[i]=i+1;
printf("enter the dependency matrix:\n");
printf("\t enter 1 if e1->e2 \n\t enter -1, if e2->e1 \n\t else enter 0 \n\n");
for(i=0;i<e2;i++)
printf("\te2%d",i+1);
for(i=0;i<e1;i++)
{
printf("\n e1%d \t",i+1);
for(j=0;j<e2;j++)
scanf("%d",&dep[i][j]);
}

for(i=0;i<e1;i++)
{
for(j=0;j<e2;j++)
{
if(dep[i][j]==1) //change the timestamp if dependency exist
{
p2[j]=max1(p2[j],p1[i]+1);

for(k=j;k<e2;k++)
p2[k+1]=p2[k]+1;
}
if(dep[i][j]==-1) //change the timestamp if dependency exist
{
p1[i]=max1(p1[i],p2[j]+1);
for(k=i;k<e1;k++)
p2[k+1]=p1[k]+1;
}
}
}
printf("P1 : "); //to print the outcome of Lamport Logical Clock
for(i=0;i<e1;i++)
{
printf("%d",p1[i]);
}
printf("\n P2 : ");
for(j=0;j<e2;j++)
printf("%d",p2[j]);
getch();
return 0 ;
}
Output:
Experiment No. 2
Objective: Simulate the Distributed Mutual Exclusion in ‘C’

Source Code:

Mutex1.c

#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 );
}

Join1.c

#include<stdio.h>
#include<stdlib.h>
#define NTHREADS 10
void *thread_function(void *);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
main()
{
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 );
}

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;
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".
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);
}
}

Output:
mutex1.c
Compile: cc -lpthread mutex1.c Run: ./a.out Results: Counter value: 1 Counter
value: 2
Join1.c
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
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
Experiment No. 3
Objective: Implement a Distributed Chat Server using TCP Sockets in ‘C’.

Source Code:

Client

//TCP Client

#include<sys/socket.h>

#include<stdio.h>

#include<string.h>

#include<netdb.h>

#include<stdlib.h>

int main()

char buf[100];

int k;

int sock_desc;

struct sockaddr_in client;

memset(&client,0,sizeof(client));

sock_desc=socket(AF_INET,SOCK_STREAM,0);

if(sock_desc==-1)

printf(“Error in socket creation”);


exit(1);

client.sin_family=AF_INET;

client.sin_addr.s_addr=INADDR_ANY;

client.sin_port=3002;

k=connect(sock_desc,(struct sockaddr*)&client,sizeof(client));

if(k==-1)

printf(“Error in connecting to server”);

exit(1);

while(1)

printf(“\nEnter data to be send to server: “);

fgets(buf,100,stdin);

if(strncmp(buf,”end”,3)==0)//Use “end” to end communication with server

break;

k=send(sock_desc,buf,100,0);

if(k==-1)

printf(“Error in sending”);

exit(1);

}
k=recv(sock_desc,buf,100,0);

if(k==-1)

printf(“Error in receiving”);

exit(1);

printf(“Message got from server is : %s”,buf);

close(sock_desc);

exit(0);

return 0;

Server

//TCP server

#include<sys/socket.h>

#include<stdio.h>

#include<string.h>

#include<netdb.h>

#include<stdlib.h>

int main()

char buf[100];

int k;
socklen_t len;

int sock_desc,temp_sock_desc;

struct sockaddr_in server,client;

memset(&server,0,sizeof(server));

memset(&client,0,sizeof(client));

sock_desc=socket(AF_INET,SOCK_STREAM,0);

if(sock_desc==-1)

printf(“Error in socket creation”);

exit(1);

server.sin_family=AF_INET;

server.sin_addr.s_addr=inet_addr(“127.0.0.1”);

server.sin_port=3002;

k=bind(sock_desc,(struct sockaddr*)&server,sizeof(server));

if(k==-1){

printf(“Error in binding”);

exit(1);

k=listen(sock_desc,20);

if(k==-1)

printf(“Error in listening”);
exit(1);

len=sizeof(client);//VERY IMPORTANT

temp_sock_desc=accept(sock_desc,(struct sockaddr*)&client,&len);//VERY
//IMPORTANT

if(temp_sock_desc==-1)

printf(“Error in temporary socket creation”);

exit(1);

while(1)

k=recv(temp_sock_desc,buf,100,0);

if(k==-1)

printf(“Error in receiving”);

exit(1);

printf(“Message got from client is : %s”,buf);

printf(“\nEnter data to be send to client: “);

fgets(buf,100,stdin);

if(strncmp(buf,”end”,3)==0)

break;
k=send(temp_sock_desc,buf,100,0);

if(k==-1)

printf(“Error in sending”);

exit(1);

close(temp_sock_desc);

exit(0);

return 0;

Output:

[root@localhost ~]$ gcc -o c tcpc.c

[root@localhost ~]$ ./c

Enter data to be send to server: hi

Message got from server is : how are u?

Enter data to be send to server: i am fine

Message got from server is : i am fine

Enter data to be send to server: end

[root@localhost ~]$

Server

[root@localhost ~]$ gcc -o s tcps.c


[root@localhost ~]$ ./s

Message got from client is : hi

Enter data to be send to client: how are u?

Message got from client is : i am fine

Enter data to be send to client: end

[root@localhost ~]$
Experiment No. 4
Objective: Implement RPC mechanism for a file transfer across a network in ‘C’

Source Code:
The Server
// server code for UDP socket programming
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define IP_PROTOCOL 0
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0
#define nofile "File Not Found!"

// function to clear buffer


void clearBuf(char* b)
{
int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function to encrypt
char Cipher(char ch)
{
return ch ^ cipherKey;
}

// function sending file


int sendFile(FILE* fp, char* buf, int s)
{
int i, len;
if (fp == NULL) {
strcpy(buf, nofile);
len = strlen(nofile);
buf[len] = EOF;
for (i = 0; i <= len; i++)
buf[i] = Cipher(buf[i]);
return 1;
}

char ch, ch2;


for (i = 0; i < s; i++) {
ch = fgetc(fp);
ch2 = Cipher(ch);
buf[i] = ch2;
if (ch == EOF)
return 1;
}
return 0;
}

// driver code
int main()
{
int sockfd, nBytes;
struct sockaddr_in addr_con;
int addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = INADDR_ANY;
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM, IP_PROTOCOL);

if (sockfd < 0)
printf("\nfile descriptor not received!!\n");
else
printf("\nfile descriptor %d received\n", sockfd);

// bind()
if (bind(sockfd, (struct sockaddr*)&addr_con, sizeof(addr_con)) == 0)
printf("\nSuccessfully binded!\n");
else
printf("\nBinding Failed!\n");

while (1) {
printf("\nWaiting for file name...\n");

// receive file name


clearBuf(net_buf);

nBytes = recvfrom(sockfd, net_buf,


NET_BUF_SIZE, sendrecvflag,
(struct sockaddr*)&addr_con, &addrlen);

fp = fopen(net_buf, "r");
printf("\nFile Name Received: %s\n", net_buf);
if (fp == NULL)
printf("\nFile open failed!\n");
else
printf("\nFile Successfully opened!\n");

while (1) {

// process
if (sendFile(fp, net_buf, NET_BUF_SIZE)) {
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen);
break;
}

// send
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag,
(struct sockaddr*)&addr_con, addrlen);
clearBuf(net_buf);
}
if (fp != NULL)
fclose(fp);
}
return 0;
}

The Client
// client code for UDP socket programming
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#define IP_PROTOCOL 0
#define IP_ADDRESS "127.0.0.1" // localhost
#define PORT_NO 15050
#define NET_BUF_SIZE 32
#define cipherKey 'S'
#define sendrecvflag 0

// function to clear buffer


void clearBuf(char* b)
{
int i;
for (i = 0; i < NET_BUF_SIZE; i++)
b[i] = '\0';
}

// function for decryption


char Cipher(char ch)
{
return ch ^ cipherKey;
}

// function to receive file


int recvFile(char* buf, int s)
{
int i;
char ch;
for (i = 0; i < s; i++) {
ch = buf[i];
ch = Cipher(ch);
if (ch == EOF)
return 1;
else
printf("%c", ch);
}
return 0;
}

// driver code
int main()
{
int sockfd, nBytes;
struct sockaddr_in addr_con;
int addrlen = sizeof(addr_con);
addr_con.sin_family = AF_INET;
addr_con.sin_port = htons(PORT_NO);
addr_con.sin_addr.s_addr = inet_addr(IP_ADDRESS);
char net_buf[NET_BUF_SIZE];
FILE* fp;

// socket()
sockfd = socket(AF_INET, SOCK_DGRAM,
IP_PROTOCOL);

if (sockfd < 0)
printf("\nfile descriptor not received!!\n");
else
printf("\nfile descriptor %d received\n", sockfd);

while (1) {
printf("\nPlease enter file name to receive:\n");
scanf("%s", net_buf);
sendto(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct sockaddr*)&addr_con,
addrlen);

printf("\n---------Data Received---------\n");

while (1) {
// receive
clearBuf(net_buf);
nBytes = recvfrom(sockfd, net_buf, NET_BUF_SIZE,
sendrecvflag, (struct
sockaddr*)&addr_con,
&addrlen);

// process
if (recvFile(net_buf, NET_BUF_SIZE)) {
break;
}
}
printf("\n-------------------------------\n");
}
return 0;
}

Output
For server
For Client
Experiment No. 5
Objective: Implement ‘Java RMI’ mechanism for accessing methods of remote
systems.

Source Code:

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;
}

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);
}
}
}

Experiment No. 6
Objective: Simulate Balanced Sliding Window Protocol in ‘C’.

Source Code:

#include<stdio.h>
#include<iostream>
#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;
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!"<<end1;
cin>>sp;
cout <<"Please enter destination file's name!"<<end1;
cin>> dp;
lable2: cout <<"Please choose size of sliding window 2--7"<<end1;
cin>> slidingWin;
if((slidingWin >7 )| (slidingWin < 2))
{ cout << "wrong enter"<<cout1;
Goto label2;
}
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; }
//use frameSize to decide the size of data array in structure 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..."<<end1;
//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!" <<end1;
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;
}
//This loop is used to fill the characters read from opened file to char array data
which
//is a member of the structure frame.
//we have to reserve 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;
//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)
{
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;*/
}

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.

Experiment No. 7
Objective: Implement CORBA mechanism by using ‘C++’ program at one end
and ‘Java program on the other.

Source Code

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);
// 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;
}
►SOURCE CODE
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;
}
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();
} 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;
}

You might also like