Index: S.No Name of Program Date Remark

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 27

INDEX

S.NO NAME OF PROGRAM DATE REMARK

Simulate the functioning of


1. Lamport’s Logical Clock.
Implement a Distributed Chat
2. Server using TCP Sockets.
Implement RPC mechanism for a
3. file transfer across a network.
Implement CORBA mechanism.
4.
Implement ‘Java RMI’ mechanism
5. for accessing methods of remote
systems.
/*program to implement lamports logical clock*/

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int n,i,a[100],m,j,c[100][100],d[100],temp,s[100][100],g,r[100][100];
clrscr();
printf("\nenter the no. of process in the distributed system=");
scanf("%d",&n);
for(i=0;i<n;i++) {
printf("\nenter the no. of events in each process=");
scanf("%d",&a[i]);
}
for(i=0;i<n;i++) {
printf("\nenter the drift velocity of each process");
scanf("%d",&d[i]);
}
printf("\the overall configuration of the distributed system is");
for(i=0;i<n;i++)
{
printf("\nthe process P[%d] has %d events in it and its drift rate is
%d",i,a[i],d[i]);
}
//for each process, entering happened before relationship of events within
that process
for(j=0;j<n;j++)
{
for(i=0;i<a[j];i++)
{
printf("\nenter the timestamp of %d event of process P[%d]",i+1,j);
scanf("%d",&c[j][i]);
}
}
//computing happened before reln. among the events of single process
for(j=0;j<n;j++)
{
for(i=0;i<a[j];i++)
{
if(c[j][i]>c[j][i+1])
{
temp=c[j][i];
c[j][i]=c[j][i+1];
c[j][i+1]=temp;
}
}
}
for(j=0;j<n;j++)
{
printf("\nthe non-decreasing order of events of a process P[%d] are",j);
for(i=0;i<a[j];i++)
{
printf("\nthe c[%d][%d] event with timestamp value %d is %d in the
process",j,i,c[j][i],i);
}
}
//considering the inter-process communication messages
printf("\nenter the no. of sending events=");
scanf("%d",&m);
for(g=0;g<m;g++)
{
printf("\nenter the timestamp index of send message event=");
scanf("%d\t%d",&s[j][i]);
s[j][i]=c[j][i];
}
for(g=0;g<m;g++)
{
printf("\nthe sending events in the distributed system are s[%d][%d] with
timestamp values %d",j,i,s[j][i]);
}
//establishing happened before relationship among the events of the processes
//using the implementation rule 1 and 2
c[j][i]=c[j][i]+d[j];//incrementing the values
//for IPC
c[j][i]=max(c[j][i]
getch();
}
Distributed Chat Server using TCP Sockets

/*
A basic extension of the java.applet.Applet class
*/
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class chatServer extends Applet
{
client clientObject;
String line;
public void init()
{
super.init();
setLayout(null);
addNotify();
resize(640,480);
txtName = new java.awt.TextField();
txtName.setText("ID");
txtName.reshape(72,12,168,27);
txtName.setFont(new Font("Dialog", Font.BOLD, 14));
txtName.setBackground(new Color(16776960));
add(txtName);
lblIp = new java.awt.Label("IP Address");
lblIp.reshape(240,12,96,24);
lblIp.setFont(new Font("Dialog", Font.BOLD, 14));
add(lblIp);
lblPort = new java.awt.Label("Port");
lblPort.reshape(480,12,48,24);
lblPort.setFont(new Font("Dialog", Font.BOLD, 14));
add(lblPort);
txtPort = new java.awt.TextField();
txtPort.setText("4321");
txtPort.reshape(528,12,72,27);
txtPort.setFont(new Font("Dialog", Font.BOLD, 14));
txtPort.setBackground(new Color(16776960));
add(txtPort);
txtArea = new java.awt.TextArea();
txtArea.setEditable(false);
txtArea.reshape(24,72,588,288);
txtArea.setBackground(new Color(65535));
add(txtArea);
btnConnect = new java.awt.Button("Connect");
btnConnect.reshape(276,432,84,34);
add(btnConnect);
txtField = new java.awt.TextField();
txtField.reshape(24,384,587,32);
txtField.setFont(new Font("Dialog", Font.BOLD, 14));
txtField.setBackground(new Color(16776960));
add(txtField);
txtIPaddr = new java.awt.TextField();
txtIPaddr.setText("161.178.121.1");
txtIPaddr.reshape(336,12,144,27);
txtIPaddr.setFont(new Font("Dialog", Font.BOLD, 14));
txtIPaddr.setBackground(new Color(16776960));
add(txtIPaddr);
label1 = new java.awt.Label("Enter your ID and press connect to begin");
label1.reshape(156,48,312,19);
label1.setFont(new Font("Dialog", Font.BOLD, 14));
label1.setBackground(new Color(12632256));
add(label1);
lblName = new java.awt.Label("Name");
lblName.reshape(12,12,60,24);
lblName.setFont(new Font("Dialog", Font.BOLD, 14));
add(lblName);
}
public boolean action(Event event, Object arg)
{
if (event.target == btnConnect)
{
btnConnect.disable();
txtField.requestFocus();
clientObject = new client(this, txtIPaddr.getText(),
txtPort.getText());
return true;
}
if (event.target == txtField)
{
line = txtField.getText();
txtField.setText("");
String lineOut = "00000000|" + txtName.getText() + "|" + line
+ "|";
clientObject.pout.println(lineOut);
return true;
}
return super.action(event, arg);
}
java.awt.TextField txtName;
java.awt.Label lblIp;
java.awt.Label lblPort;
java.awt.TextField txtPort;
java.awt.TextArea txtArea;
java.awt.Button btnConnect;
java.awt.TextField txtField;
java.awt.TextField txtIPaddr;
java.awt.Label label1;
java.awt.Label lblName;
}
class client extends Thread {
DataInputStream dis;
Socket sock;
PrintStream pout;
InputStream in;
OutputStream out;
DataInputStream din;
DataOutputStream dout;
String IPA;
chatServer myClient;
String port;
int portInt;
client(chatServer myClient, String IPA, String port) {
this.myClient = myClient;
this.IPA = IPA;
this.port = port;
portInt = Integer.valueOf(port).intValue();
start();
}
public void run() {
System.out.println("client thread started");
try {
sock = new Socket(IPA, portInt);
System.out.println("connection made");
in = sock.getInputStream();
out = sock.getOutputStream();
pout = new PrintStream(out);
din = new DataInputStream(in);
dout = new DataOutputStream(out);
while(true) {
String request = din.readLine();
myClient.txtArea.appendText(request + "\n");
}
}
catch (UnknownHostException e ) {System.out.println("can't find host"); }
catch ( IOException e ) {System.out.println("Error connecting to host");}
}
}
RPC mechanism

//======================================================== file = local.c


=====
//= Local program to send an executable file to a remote for execution
=
//= - remote.c is the receiving remote executor
=
//============================================================================
=
//= Notes:
=

//= 1) This program should be run only after starting remote


=
//=---------------------------------------------------------------------------
=
//= Sample execution (131.247.167.106 is IP address where remote running)+
=
//=
=
//= d:\work>local 131.247.167.106 hello.exe outfile.txt
=
//= Sending 'hello.exe' to remote server on '131.247.167.106'
=
//= 'hello.exe' is executing on remote server
=
//= Execution of 'hello.exe' and transfer of output to 'outfile.txt' done!
=

//----- Include files


---------------------------------------------------------
#include <stdio.h> // Needed for printf()
#include <stdlib.h> // Needed for exit()
#include <string.h> // Needed for memcpy() and strcpy()
#include <windows.h> // Needed for Sleep() and Winsock stuff
#include <fcntl.h> // Needed for file i/o constants
#include <sys\stat.h> // Needed for file i/o constants
#include <io.h> // Needed for open(), close(), and eof()

//----- Defines -------------------------------------------------------------


#define PORT_NUM 1050 // Arbitrary port number for the server
#define MAX_LISTEN 1 // Maximum number of listens to queue
#define SIZE 256 // Size in bytes of transfer buffer

//===== Main program


==========================================================
void main(int argc, char *argv[])
{
WORD wVersionRequested = MAKEWORD(1,1); // WSA functions
WSADATA wsaData; // Winsock API data structure

unsigned int remote_s; // Remote socket descriptor


struct sockaddr_in remote_addr; // Remote Internet address
struct sockaddr_in server_addr; // Server Internet address
unsigned char bin_buf[SIZE]; // Buffer for file tranfer
unsigned int fh; // File handle
unsigned int length; // Length of buffers transferred
struct hostent *host; // Structure for gethostbyname()
struct in_addr address; // Structure for Internet address
char host_name[256]; // String for host name
int addr_len; // Internet address length
unsigned int local_s; // Local socket descriptor
struct sockaddr_in local_addr; // Local Internet address
struct in_addr remote_ip_addr; // Remote IP address

// Check if number of command line arguments is valid


if (argc !=4)
{
printf(" *** ERROR - Must be 'local (host) (exefile) (outfile)' \n");
printf(" where host is the hostname *or* IP address \n");
printf(" of the host running remote.c, exefile is the \n");
printf(" name of the file to be remotely run, and \n");
printf(" outfile is the name of the local output file. \n");
exit(1);
}

// Initialization of winsock
WSAStartup(wVersionRequested, &wsaData);

// Copy host name into host_name


strcpy(host_name, argv[1]);

// Do a gethostbyname()
host = gethostbyname(argv[1]);
if (host == NULL)
{
printf(" *** ERROR - IP address for '%s' not be found \n", host_name);
exit(1);
}

// Copy the four-byte client IP address into an IP address structure


memcpy(&address, host->h_addr, 4);

// Create a socket for remote


remote_s = socket(AF_INET, SOCK_STREAM, 0);

// Fill-in the server (remote) socket's address information and connect


// with the listening server.
server_addr.sin_family = AF_INET; // Address family to use
server_addr.sin_port = htons(PORT_NUM); // Port num to use
server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(address)); // IP address
connect(remote_s, (struct sockaddr *)&server_addr, sizeof(server_addr));

// Open and read *.exe file


if((fh = open(argv[2], O_RDONLY | O_BINARY, S_IREAD | S_IWRITE)) == -1)
{
printf(" EROR - Unable to open file '%s'\n", argv[2]);
exit(1);
}

// Output message stating sending executable file


printf("Sending '%s' to remote server on '%s' \n", argv[2], argv[1]);

// Send *.exe file to remote


while(!eof(fh))
{
length = read(fh, bin_buf, SIZE);
send(remote_s, bin_buf, length, 0);
}

// Close the *.exe file that was sent to the server (remote)
close(fh);

// Close the socket


closesocket(remote_s);

// Cleanup Winsock
WSACleanup();

// Output message stating remote is executing


printf(" '%s' is executing on remote server \n", argv[2]);

// Delay to allow everything to clean-up


Sleep(100);

// Initialization of winsock
WSAStartup(wVersionRequested, &wsaData);

// Create a new socket to receive output file from remote server


local_s = socket(AF_INET, SOCK_STREAM, 0);

// Fill-in the socket's address information and bind the socket


local_addr.sin_family = AF_INET; // Address family to use
local_addr.sin_port = htons(PORT_NUM); // Port num to use
local_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on any IP addr
bind(local_s, (struct sockaddr *)&local_addr, sizeof(local_addr));

// Listen for connections (queueing up to MAX_LISTEN)


listen(local_s, MAX_LISTEN);

// Accept a connection, the accept will block and then return with
// remote_addr filled in.
addr_len = sizeof(remote_addr);
remote_s = accept(local_s, (struct sockaddr*)&remote_addr, &addr_len);

// Copy the four-byte client IP address into an IP address structure


memcpy(&remote_ip_addr, &remote_addr.sin_addr.s_addr, 4);

// Create and open the output file for writing


if ((fh=open(argv[3], O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
S_IREAD | S_IWRITE)) == -1)
{
printf(" *** ERROR - Unable to open '%s'\n", argv[3]);
exit(1);
}

// Receive output file from server


length = SIZE;
while(length > 0)
{
length = recv(remote_s, bin_buf, SIZE, 0);
write(fh, bin_buf, length);
}

// Close output file that was received from the remote


close(fh);

// Close the sockets


closesocket(local_s);
closesocket(remote_s);

// Output final status message


printf("Execution of '%s' and transfer of output to '%s' done! \n",
argv[2], argv[3]);

// Cleanup Winsock
WSACleanup();
}

//======================================================= file = remote.c


=====
//= Remote server to receive and execute a *.exe file, stdout is returned
=
//= - local.c is the sending client
=
//============================================================================
=
//= Notes:
=
//= 1) This program should be started before running local
=
//=---------------------------------------------------------------------------
=
//= Sample execution:
=
//=
=
//= d:\work>remote
=
//= Waiting for a connection...
=
//= Connection established, receiving remote executable file
=
//= Executing remote executable (stdout to output file)
=
//= Waiting for a connection...
=

//----- Include files


---------------------------------------------------------
#include <stdio.h> // Needed for printf()
#include <stdlib.h> // Needed for exit()
#include <string.h> // Needed for memcpy() and strcpy()
#include <windows.h> // Needed for Sleep() and Winsock stuff
#include <fcntl.h> // Needed for file i/o constants
#include <sys\stat.h> // Needed for file i/o constants
#include <io.h> // Needed for open(), close(), and eof()

//----- Defines -------------------------------------------------------------


#define PORT_NUM 1050 // Arbitrary port number for the server
#define MAX_LISTEN 1 // Maximum number of listens to queue
#define IN_FILE "run.exe" // Name given to transferred *.exe file
#define TEXT_FILE "output" // Name of output file for stdout
#define SIZE 256 // Size in bytes of transfer buffer

//===== Main program


==========================================================
void main(void)
{
WORD wVersionRequested = MAKEWORD(1,1); // WSA functions
WSADATA wsaData; // WSA functions

unsigned int remote_s; // Remote socket descriptor


struct sockaddr_in remote_addr; // Remote Internet address
struct sockaddr_in server_addr; // Server Internet address
unsigned int local_s; // Local socket descriptor
struct sockaddr_in local_addr; // Local Internet address
struct in_addr local_ip_addr; // Local IP address
int addr_len; // Internet address length
unsigned char bin_buf[SIZE]; // File transfer buffer
unsigned int fh; // File handle
unsigned int length; // Length of buffers transferred

// Do forever
while(1)
{
// Winsock initialization
WSAStartup(wVersionRequested, &wsaData);

// Create a socket
remote_s = socket(AF_INET, SOCK_STREAM, 0);
// Fill-in my socket's address information and bind the socket
remote_addr.sin_family = AF_INET; // Address family to use
remote_addr.sin_port = htons(PORT_NUM); // Port number to use
remote_addr.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on any IP addr
bind(remote_s, (struct sockaddr *)&remote_addr, sizeof(remote_addr));

// Output waiting message


printf("Waiting for a connection... \n");

// Listen for connections (queueing up to MAX_LISTEN)


listen(remote_s, MAX_LISTEN);

// Accept a connection, accept() will block and return with local_addr


addr_len = sizeof(local_addr);
local_s = accept(remote_s, (struct sockaddr *)&local_addr, &addr_len);

// Copy the four-byte client IP address into an IP address structure


memcpy(&local_ip_addr, &local_addr.sin_addr.s_addr, 4);

// Output message acknowledging receipt, saving of *.exe


printf(" Connection established, receiving remote executable file \n");

// Open IN_FILE for remote executable file


if((fh = open(IN_FILE, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
S_IREAD | S_IWRITE)) == -1)
{
printf(" *** ERROR - unable to open executable file \n");
exit(1);
}

// Receive executable file from local


length = 256;
while(length > 0)
{
length = recv(local_s, bin_buf, SIZE, 0);
write(fh, bin_buf, length);
}

// Close the received IN_FILE


close(fh);

// Close sockets
closesocket(remote_s);
closesocket(local_s);

// Cleanup Winsock
WSACleanup();

// Print message acknowledging execution of *.exe


printf(" Executing remote executable (stdout to output file) \n");

// Execute remote executable file (in IN_FILE)


system(IN_FILE ">" TEXT_FILE);

// Winsock initialization to re-open socket to send output file to local


WSAStartup(wVersionRequested, &wsaData);
// Create a socket
// - AF_INET is Address Family Internet and SOCK_STREAM is streams
local_s = socket(AF_INET, SOCK_STREAM, 0);

// Fill in the server's socket address information and connect with


// the listening local
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT_NUM);
server_addr.sin_addr.s_addr = inet_addr(inet_ntoa(local_ip_addr));
connect(local_s, (struct sockaddr *)&server_addr, sizeof(server_addr));

// Print message acknowledging transfer of output to client


printf(" Sending output file to local host \n");

// Open output file to send to client


if((fh = open(TEXT_FILE, O_RDONLY | O_BINARY, S_IREAD | S_IWRITE)) == -1)
{
printf(" *** ERROR - unable to open output file \n");
exit(1);
}

// Send output file to client


while(!eof(fh))
{
length = read(fh, bin_buf, SIZE);
send(local_s, bin_buf, length, 0);
}

// Close output file


close(fh);

// Close sockets
closesocket(remote_s);
closesocket(local_s);

// Cleanup Winsock
WSACleanup();

// Delay to allow everything to clean-up


Sleep(100);
}
}
CORBA Mechanism

Developing a simple client / server


For the development of a basic client/server in CORBA, I have used the Orbacus ORB that
you can find here. It's a free ORB for non-commercial purposes, with an unlimited time of
use. The package is available for both Java and C++, and the specification is up-to-date
CORBA compliant.

The business logic domain

The demo application is inspired by a cryptographic service where the client makes a
request for encrypting and decrypting a plaint text to a server which performs the
operations. The encryption algorithm is based on the Caesar cipher, which is one of the
simplest encryption techniques. It's a type of substitution cipher in which each letter in the
plain text is replaced by a letter, some fixed number of positions down the alphabet.
Besides this technique, I added a XOR operation with an encryption key after the shift
operation to obscure the relationship. In the image below, you can see this technique:
Caesar cipher

Implementing the servant class

The next step is to implement the servant class. For this purpose, we will need to create a
class for the servant that inherits from the skeleton class, as shown below:

#include "OB/CORBA.h"

#include "crypt_skel.h"
#include <iostream>
#include <string>

class CryptographicImpl : virtual public ::POA_CaesarAlgorithm,


virtual public PortableServer::RefCountServantBase

{
public:

CryptographicImpl() {}

// Caesar text encryption algorithm


::CaesarAlgorithm::charsequence* encrypt(const char* info,
::CORBA::ULong k,::CORBA::ULong shift)
throw(::CORBA::SystemException)
{
std::string msg = info;
int len = msg.length();
::CaesarAlgorithm::charsequence* outseq =
new ::CaesarAlgorithm::charsequence;
outseq->length(len + 1);
std::string::iterator i = msg.begin();
std::string::iterator end = msg.end();
int j = 0;
while (i != end)
{
*i+= shift;
*i ^= k;
(*outseq)[j++] = *i++;
}
(*outseq)[len] = '\0';
return outseq;

// Caesar text decryption algorithm


char* decrypt(const ::CaesarAlgorithm::charsequence& info,
::CORBA::ULong k,::CORBA::ULong shift)
throw(::CORBA::SystemException)
{
char* r = CORBA::string_alloc(info.length());

for (int i = 0;i < info.length() - 1;i++)


{
r[i] = info[i];
r[i] ^= k;
r[i] -= shift;

}
r[info.length() - 1] = '\0';
return r;
}
};

The servant implements the CORBA object methods functionality. The servant is called by
the skeleton when a client calls a CORBA object method implemented by the servant. The
Orbacus IDL compiler generates an empty implementation of the servant, called
cryptimpl.h.

Creating the server

Before ending the server side implementation, it's necessary to create an entry point that
instantiates and activates the servant class. We will have to implement a server with the
CORBA initialization. The following code explains this issue:

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


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

// Get a reference to the root POA


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

3 policies[0] =
rootPOA-
>create_thread_policy(PortableServer::SINGLE_THREAD_MODEL);
// Get the POA manager object
4 PortableServer::POAManager_var manager = rootPOA->the_POAManager();

// Create a new POA with specified policies


PortableServer::POA_var myPOA =
rootPOA->create_POA("myPOA", manager, policies);
// Get a reference to the Naming Service root_context
5 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


6 CryptographicImpl* CrypImpl = new CryptographicImpl();
// Activate object
PortableServer::ObjectId_var myObjID = myPOA-
>activate_object(CrypImpl);
// Get a CORBA reference with the POA through the servant
7 CORBA::Object_var o = myPOA->servant_to_reference(CrypImpl);
// Get a reference to the CaesarAlgorithm interface
8 CaesarAlgorithm_var cav = CaesarAlgorithm::_narrow(o);
// The reference is converted to a character string
9 CORBA::String_var s = orb->object_to_string(cav);
cout << "The IOR of the object is: " << s << 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
10 nc->rebind(name,o);

// Activate the POA


manager->activate();
cout << "The server is ready. Awaiting for incoming requests..."
<< endl;
// Start the ORB
11 orb -> run();

} catch(const CORBA::Exception& e) {
// Handles CORBA exceptions
cerr << e << endl;
return 1;
}
return 0;
}
1. Initializes the CORBA ORB.
2. Gets the root POA. The server object must be registered using an object adapter. In
this case, we register the object in the root POA. In most cases, this object adapter
is enough.

3. Set the POA policies to SINGLE_THREAD_MODEL. This POA policy manages one
request at a time, instead of multithreading, so we get it multithread-aware. If you
want to use multithread capabilities, read a CORBA book about JTCThreads. This
approach is safe and clear, but has bad performance.
4. A POA Manager is obtained. The Manager controls a set of object adapters, allowing
them to work.

5. A reference to the Name Service is obtained. It will allow to register an object


reference in a naming context.

6. A servant CryptographicImpl object is dynamically created.

7. The POA method servant_to_reference is used to obtain a CORBA reference


from a servant.

8. The reference is converted to a CaesarAlgorithm interface reference.

9. The reference is converted to a character string in order to display it.

10. The CORBA reference from a servant is registered in the Name Service using a
naming context, through a call to rebind.

11. Finally, the ORB starts and keeps awaiting requests.

Implementing the client

The client side is a program that allows to communicate with the remote CORBA object
instantiated in a server. The following code is a sample of a client invoking the remote
object:

#include <iostream>
#include <string>
#include "OB/CORBA.h"
#include "OB/Cosnaming.h"
#include "crypt.h" // Include the stub

using namespace std;

int main(int argc, char** argv)


{

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

// Get a reference to the Naming Service


2 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
3 CORBA::Object_var managerObj = nc->resolve(name);
// Narrow the previous object to obtain the correct type
4 ::CaesarAlgorithm_ptr manager =
::CaesarAlgorithm::_narrow(managerObj.in());

string info_in,info_out,exit,dummy;
::CaesarAlgorithm::charsequence* 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());

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


cout << "Enter a plain text to encrypt: ";
getline(cin,info_in);

// Invoke first remote method


5 inseq = manager->encrypt(info_in.c_str(),key,shift);
cout << "----------------------------------------------" <<
endl;
cout << "Encrypted text is: " << inseq->get_buffer() << endl;
// Invoke second remote method
6 info_out = manager->decrypt(*inseq,key,shift);
cout << "Decrypted text is: " << info_out << endl;
cout << "----------------------------------------------" <<
endl;
cout << "Exit? (y/n): ";
cin >> exit;
} while (exit!="y");
} catch(const std::exception& std_e){
cerr << std_e.what() << endl;
return 1;
}
}catch(const CORBA::Exception& e) {
// Handles CORBA exceptions
cerr << e << endl;
return 1;
}
return 0;
}
1. Initialize the CORBA ORB.
2. Get a reference to the Name Service object.

3. Invoke the root context to retrieve the object reference.

4. Get a pointer to the CaesarAlgorithm interface from the CORBA object reference.

5. Invoke the first remote method, passing three input arguments, and return a CORBA
sequence.

6. Invoke the second remote method, passing the previous returned sequence by
value.

Working all together

Once we have implemented the client and the server, it's time to connect them. Let's start
with the server. Previously, to run it, we had to call the Orbacus Name Service application
by searching for nameserv.exe. Therefore, the call must be done in this form:

nameserv -OAhost localhost -OAport 8140

Instead of using the localhost, we can use an external LAN or Internet IP address by
replacing localhost with the IP.

After this, we can execute the server with these parameters:

server -ORBInitRef NameService=corbaloc:iiop:localhost:8140/NameService

It's also possible to replace localhost with an external IP.

We will get the following result:

Finally, we can proceed to call the client by prompting the following:

client -ORBInitRef NameService=corbaloc:iiop:localhost:8140/NameService


and we will get a client application running and connecting with the server through the
Internet:
JAVA RMI

Objective:

Implement Java RMI mechanism for accessing methods of a Remote System.

Theory:

RMI applications are often comprised of two separate programs : a server and client to invoke the
events and some of object make reference to them accessible and wait for client to invoke methods on
these objects.

A typical application gets remote reference to one or more remote objects in the server and the client
and pass information back and forth.

Distributed Remote Objects

1. Locate remote objects


2. Communicate with remote object

RMI = RPC + Object Orientation

SERVER CLIENT

Request message
do operation
.
. Get request
Reply Message
(wait)
Select object
.
Execute
(continue)
Method
Request – Reply Communication for RMI

Client Server
Skeleton of B
Request
Object A Object B Remote Objects B

Reply
Remote Reference Remote Reference
Module
Module Communication

Role of proxy skeleton in RMI

Skeleton & Dispatcher for B’s Class

Request
Object Proxy for Remote Object for B

A B

Reply
Role of Proxy & Skeleton in RMI

import java.io.*;
import java.net.*;
class client1 {

public static void main(String args[]) throws IOException,UnknownHostException


{
String message;
String return_message;

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6789);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

message = inFromUser.readLine();

outToServer.writeBytes(message + '\n');

return_message = inFromServer.readLine();

System.out.println("FROM SERVER: " + return_message);

clientSocket.close();

}
}
import java.io.*;
import java.net.*;
class client2 {

public static void main(String args[]) throws IOException,UnknownHostException


{
String message;
String return_message;

BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("localhost", 6790);

DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));

message = inFromUser.readLine();

outToServer.writeBytes(message + '\n');

return_message = inFromServer.readLine();

System.out.println("FROM SERVER: " + return_message);

clientSocket.close();

}
}

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

class server {

public static void main(String argv[]) throws IOException,UnknownHostException


{
String client_msg1,client_msg2;
String msg_client1,msg_client2;

ServerSocket welcomeSocket1 = new ServerSocket(6789);


ServerSocket welcomeSocket2 = new ServerSocket(6790);

while(true) {

Socket connectionSocket1 = welcomeSocket1.accept();

//For client1;

BufferedReader inFromClient1 =
new BufferedReader(new
InputStreamReader(connectionSocket1.getInputStream()));

DataOutputStream outToClient1 =
new DataOutputStream(connectionSocket1.getOutputStream());

//for client2;
Socket connectionSocket2 = welcomeSocket2.accept();
BufferedReader inFromClient2 =
new BufferedReader(new
InputStreamReader(connectionSocket2.getInputStream()));

DataOutputStream outToClient2 =
new DataOutputStream(connectionSocket2.getOutputStream());

client_msg1 = inFromClient1.readLine();
msg_client2 = client_msg1+ '\n';
outToClient2.writeBytes(msg_client2);

client_msg2=inFromClient2.readLine();
msg_client1=client_msg2+'\n';
outToClient1.writeBytes(msg_client1);
}
}
}

You might also like