Vous êtes sur la page 1sur 27

Developing Calculator application with RMI Edition

Developing Calculator application


with RMI Edition
Professor: Sheau-Ling Hsieh , Ph.D

Team : Chi-Hua Chen 9634501 Chang-Min Chen 9634508


Ying-Yu Lin 9634509 Hsin-Ying Hsieh 9634512
Ming-Chia Li 9634519 Chia-Wei Hsu 9634524
Yin-Lung Lu 9634528

Institute of Information Management,


National Chiao Tung University, Hsinchu, Taiwan.

1/27
Developing Calculator application with RMI Edition

Contents
1. Introduction..........................................................................................................3
2. Objective ...............................................................................................................5
3. Hardware & Software Environment..................................................................5
3.1 Hardware ..................................................................................................5
3.2 Software ....................................................................................................5
4. Approach (Design) ...............................................................................................5
5. Implementation ....................................................................................................6
5.1 The Server Side ........................................................................................7
5.1.1 Creating the Interface.........................................................................7
5.1.2 Implementation of the remote service...............................................8
5.1.3 Implementation of the remote service.............................................10
5.2 The Client Side .......................................................................................11
6. Results (Execution) ............................................................................................13
6.1 Compiling the Stubs...............................................................................13
6.2 Starting the Server.................................................................................13
6.3 Running the Client.................................................................................13
7. Alternatives and Discussion ..............................................................................15
7.1 Example services ....................................................................................17
7.2 Client-side stub and client coding.........................................................17
7.3 Result.......................................................................................................18
7.3.1 Costs associated directly with communications protocols ............18
7.3.2 Costs of document transfer ..............................................................20
7.3.3 Common implementation for Java RMI, SOAP, and CORBA ....20
8. Conclusion ..........................................................................................................26
9. References...........................................................................................................27

2/27
Developing Calculator application with RMI Edition

1. Introduction
This paper is divided into three sections. Part I starts with an introduction to the
core infrastructure and the basic features of RMI . Part II builds on the first by drilling
down on the underlying technologies ,building a RMI application and discusses the
necessary steps when building a simple RMI application.. Part III compares three
distributed object systems that they consist of SOAP,CORBA and RMI.
RMI is designed to make communication between two Java programs, running in
separate JVMs, as much like making a method call inside a single process as possible.
RMI relies on two similar types of objects that are automatically generated by the
RMI Compiler from an implementation of the server: stubs and skeletons. A stub is a
client-side object that represents a single server object inside the client's JVM. It
implements the same methods as the server object, maintains a socket connection to
the server object's JVM automatically and is responsible for marshalling and
demarshalling data on the client side. A skeleton is a server-side object responsible for
maintaining network connections and marshalling and demarshalling data on the
server side.
The basic procedure a client uses to communicate with a server is as follows:

1. The client obtains an instance of the stub class. The stub class is automatically
pregenerated from the target server class and implements all the methods that the
server class implements.
2. The client calls a method on the stub. The method call is actually the same
method call the client would make on the server object if both objects resided in the
same JVM.
3. Internally, the stub either creates a socket connection to the skeleton on the
server or reuses a pre-existing connection. It marshalls all the information associated
to the method call, including the name of the method and the arguments, and sends
this information over the socket connection to the skeleton.
4. The skeleton demarshalls the data and makes the method call on the actual server
object. It gets a return value back from the actual server object, marshalls the return
value, and sends it over the wire to the stub.
5. The stub demarshalls the return value and returns it to the client code.

Stubs and skeletons are shown in Figure 1.1.and Figure 1.2

3/27
Developing Calculator application with RMI Edition

Figure 1.1. The RMI Layer Model

Figure 1-2. A basic RMI call with a stub and skeleton

By the way , there is also a lot of RMI information available on the Internet.
Three of the best general-purpose RMI resources are:
1. Javasoft's RMI home page
This is the place to obtain the most recent information about RMI. It also
contains links to other pages containing RMI information from Javasoft. The URL is
http://java.sun.com/products/jdk/rmi/.
2. The RMI trail from the Java Tutorial
The Java Tutorial is a very good way to get your feet wet on almost any Java
topic. The RMI sections are based at
http://java.sun.com/docs/books/tutorial/rmi/index.html.
3. The RMI Users mailing list
The RMI users mailing list is a small mailing list hosted by Javasoft. All levels,

4/27
Developing Calculator application with RMI Edition

from beginner to advanced, are discussed here, and many of the world's best RMI
programmers will contribute to the discussion if you ask an interesting enough
question.The archives of the mailing list are stored at
http://archives.java.sun.com/archives/rmi-users.html.

2. Objective
Understand the structure of RMI in depth and use RMI to develop an example
application to describe the development process for creating distributed, object-based
applications for Java. Learn the process of middleware development, and understand
the RMI infrastructure and how it works, for example, suppose an object on
140.113.73.48 has a query method that looks up information in a local database. The
query method would be exported in a remote interface. The client on localhost would
look up the object in 140.113.73.48 registry, then call the query method, just as it
would call a query method in an object on localhost. The object that queries the
database runs on the server, but it accepts arguments from and returns results to the
client on localhost. This is simpler than designing and implementing a new
socket-based protocol for communication between the database server and its client.
The details of making the connections between the hosts and transferring the data are
hidden in the RMI classes.

3. Hardware & Software Environment


3.1 Hardware
AMD Semprom(tm) 1.00 GHz
512 MB RAM, Physical Address Extension

3.2 Software
Java 2, using JDK1.5.0, Java RMI 1.2 and later, the skeleton layer is omitted.
Eclipse for designing java programs.

4. Approach (Design)
The project is to create a simple calculator system that performs the functionality
of a remote calculator service. There is a single client and a single server. The server
provides a set of arithmetic methods include add, subtract, multiply, divide,log and
exp. These can be remotely invoked by the client. Therefore, the server receives a

5/27
Developing Calculator application with RMI Edition

request from the client, performs the arithmetic operation and then returns the result
back to the client. In addition , we provider a formula service to Calculate Quadratic
equation and Simultaneous Linear Equations in 2 unknown. When the client needs to
Calculate Quadratic equation and Simultaneous Linear Equations in 2 unknown , the
client calls the formula service , and when the formula service must arithmetic
operation , it will call arithmetic service.

Figure 4-1. A basic RMI procedure

5. Implementation
Most of the methods you need for working with remote objects are in three
packages: java.rmi , java.rmi.server , and java.rmi.registry. The java.rmi package
defines the classes, interfaces, and exceptions that will be seen on the client side. You
need these when you're writing programs that access remote objects but are not
themselves remote objects. The java.rmi.server package defines the classes, interfaces,
and exceptions that will be visible on the server side. You use these classes when you
are writing a remote object that will be called by clients. The java.rmi.registry
package defines the classes, interfaces, and exceptions that are used to locate and
name remote objects.
The RMI system must be composed of the following parts:
1. The Server Side
2. The Client Side
3. Compiling the Stubs
4. Starting the Server
5. Running the Client

6/27
Developing Calculator application with RMI Edition

5.1 The Server Side


5.1.1 Creating the Interface
To create a new remote object, you first define an interface that extends the
java.rmi.Remote interface. The Remote interface does not have any methods of
its own; its sole purpose is to tag remote objects so that they can be
identified as such. One definition of a remote object is an instance of a class
that implements the Remote interface, or any interface that extends Remote.
Your subinterface of Remote determines which methods of the remote object
may be called by clients. A remote object may have many public methods,
but only those declared in a remote interface can be invoked remotely. The
other public methods may be invoked only from within the virtual machine
where the object lives.
Nothing in this interface says anything about how the calculation is
implemented.

Program 1: iCalculator
public interface iCalculator extends java.rmi.Remote {
public double add(double a, double b)throws java.rmi.RemoteException;
public double sub(double a, double b)throws java.rmi.RemoteException;
public double mul(double a, double b)throws java.rmi.RemoteException;
public double div(double a, double b)throws java.rmi.RemoteException;
public double exp(double a)throws java.rmi.RemoteException;
public double log(double a)throws java.rmi.RemoteException;
public double sqrt(double a)throws java.rmi.RemoteException;
}

Program2:iFunction
public interface iFunction extends java.rmi.Remote {
//給定abc, 令ax^2+bx+c=0, 求x之值
public double[] quadratic(double first, double second, double third)
throws java.rmi.RemoteException;
//給定abc, 令ax+by+c=0, 求x,y之值
public double[] linear(double first1, double mid1, double last1,
double first2, double mid2, double last2)throws java.rmi.RemoteException;
}

7/27
Developing Calculator application with RMI Edition

5.1.2 Implementation of the remote service


Program 3, the CalculatorImpl class, implements the remote interface.This
iCalculator class has a constructor and seven methods. These methods will
be available to the client. The constructor is used on the server side but is
not available to the client.

Program 3: CalculatorImpl
import java.rmi.Naming;
public class CalculatorImpl extends java.rmi.server.UnicastRemoteObject implements iCalculator {
// Implementations must have an
//explicit constructor
// in order to declare the
//RemoteException exception
public CalculatorImpl()throws java.rmi.RemoteException {
super();
}
public double add(double a, double b)throws java.rmi.RemoteException {
return a + b;
}
public double sub(double a, double b)throws java.rmi.RemoteException {
return a - b;
}
public double mul(double a, double b)throws java.rmi.RemoteException {
return a * b;
}
public double div(double a, double b)throws java.rmi.RemoteException {
return a / b;
}
public double exp(double a)throws java.rmi.RemoteException{
return Math.exp(a);
}
public double log(double a)throws java.rmi.RemoteException{
return Math.log(a);
}
public double sqrt(double a)throws java.rmi.RemoteException{
return Math.sqrt(a);
}
}

8/27
Developing Calculator application with RMI Edition

Program4: FunctionImpl

import java.rmi.Naming;
public class FunctionImpl extends java.rmi.server.UnicastRemoteObject implements iFunction {
private iCalculator calc;
double[] ans; //求出的解
private double a;//宣告public final,可被外部讀取,但不能更動。
private double b;
private double c;
private double b2;
private double ac4;
public FunctionImpl()throws java.rmi.RemoteException {
super();
try {
calc = new CalculatorImpl();
Naming.rebind("rmi://localhost/CalculatorService", calc); //呼叫Calculator的服務
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public double[] quadratic(double first, double second, double third)throws java.rmi.RemoteException
{
ans = new double[2];
//以下加、減、乘、除、開根號等計算,皆是呼叫Calculator的服務來計算
a = first;
b = second;
c = third;
ans[0] = calc.div(calc.add(-b, calc.sqrt(calc.sub(calc.mul(b, b), calc.mul(4,calc.mul(a,c))))) ,
calc.mul(2, a));
ans[1] = calc.div(calc.sub(-b, calc.sqrt(calc.sub(calc.mul(b, b), calc.mul(4,calc.mul(a,c))))) ,
calc.mul(2, a));
eturn ans;
}
public double[] linear(double first1, double mid1, double last1,
double first2, double mid2, double last2)throws
java.rmi.RemoteException{
ans = new double[2];
a = first1;
b = mid1;

9/27
Developing Calculator application with RMI Edition

c = last1;
double d = first2;
double e = mid2;
double f = last2;
ans[0] = (c*e-f*b)/(a*e-d*b);
ans[1] = (d*c-a*f)/(d*b-a*e);
return ans;
}
}

5.1.3 Implementation of the remote service


All it has is a main( ) method. It begins by entering a try block that catches
RemoteException. Then it constructs a new Impl object and binds that object
to the name " rmi://localhost/FunctionService " or " rmi://localhost/CalculatorService "
using the Naming class to talk to the local registry. A registry keeps track of
the available objects on an RMI server and the names by which they can be
requested. When a new remote object is created, the object adds itself and
its name to the registry with the Naming.bind( ) or Naming.rebind( ) method.
Clients can then ask for that object by name or get a list of all the remote
objects that are available. Note that there's no rule that says the name the
object has in the registry has to have any necessary relation to the class
name.

Program 5: FunctionServer
import java.rmi.Naming;
public class FunctionServer {
public FunctionServer() {
try {
iFunction f = new FunctionImpl();
Naming.rebind("rmi://localhost/FunctionService", f);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public static void main(String args[]) {
new FunctionServer();
}
}

10/27
Developing Calculator application with RMI Edition

Program 6: CalculatorServer
import java.rmi.Naming;
public class CalculatorServer {
public CalculatorServer() {
try {
iCalculator c = new CalculatorImpl();
Naming.rebind("rmi://localhost/CalculatorService", c);
} catch (Exception e) {
System.out.println("Trouble: " + e);
}
}
public static void main(String args[]) {
new CalculatorServer();
}
}

5.2 The Client Side


Before a client can call a remote method, it needs to retrieve a remote reference
to the remote object. A program retrieves a remote reference by asking a registry
on the server for a remote object. It asks by calling the registry's lookup( ) method.
The exact naming scheme depends on the registry you use.

Program 7: RMIGUI
...
public class RMIGUI extends JFrame implements ActionListener{
private iFunction function;
private iCalculator cal;
...
//RMIGUI's Constructor
public RMIGUI() {
super("RMI Application");
...
//===============call the service=================
try {
function = (iFunction)Naming.lookup("rmi://localhost/FunctionService");

11/27
Developing Calculator application with RMI Edition

cal = (iCalculator)Naming.lookup("rmi://localhost/CalculatorService");
}
catch (MalformedURLException murle) {
System.out.println();
System.out.println("MalformedURLException");
System.out.println(murle);
}
catch (RemoteException re) {
System.out.println();
System.out.println("RemoteException");
System.out.println(re);
}
catch (NotBoundException nbe) {
System.out.println();
System.out.println("NotBoundException");
System.out.println(nbe);
}
catch (java.lang.ArithmeticException ae) {
System.out.println();
System.out.println("java.lang.ArithmeticException");
System.out.println(ae);
}
...
public void actionPerformed(ActionEvent evt){
//use function and cal the call the service from
CalculatorServer and FunctionServer, respectively
}
public static void main(String[] args) {
RMIGUI frame = new RMIGUI();
frame.setSize(340, 350);
frame.setResizable(false);
frame.setTitle("RMI DEMO PROGRAM");
frame.setVisible(true);
}
}

12/27
Developing Calculator application with RMI Edition

6. Results (Execution)
6.1 Compiling the Stubs
Before your server can begin accepting invocations, you must generate the stubs
and skeletons that the program requires. We have already discussed what the
stubs and skeletons do: the stub contains the information in the Remote interface
, and a skeleton is similar but on the server side. Fortunately, we don't have to
write them ourselves: they can be generated automatically from the remote
object's Java source code, using a utility called rmic included with the JDK. To
generate the stubs and skeletons for the FunctionImpl and CalculatorImpl remote
object, run rmic on the remote object's class.

%javac iCalculator.java
% javac iFunction.java
%javac –classpath . CalculatorImpl.java
%javac –classpath . FunctionImpl.java
%rmic –classpath . CalculatorImpl
%rmic –classpath . FunctionImpl

6.2 Starting the Server


you need to run, the remote object server itself and the registry that allows local
clients to connect to the remote server. Since the server expects to talk to the
Naming registry, you must start the registry first. Make sure all the stub, skeleton,
and server classes are in the server's class path and type

%javac –classpath . Calculatorserver.java


%javac –classpath . FunctionServer.java
%start rmiregistry
%java –classpath . FunctionServer
%java –classpath . Calculatorserver

6.3 Running the Client


The client sends those objects over the wire to the remote server. The server
receives each of those objects, calculates the number for that index, and sends a
object back over the Internet to the client.

13/27
Developing Calculator application with RMI Edition

%javac –classpath . RMIGUI.java


%java –classpath . RMIGUI

Figure 6.1. Four-Functions Frame

Figure 6.2. Simultaneous Linear Equations in 2 unknown Function Frame

14/27
Developing Calculator application with RMI Edition

Figure 6.3. Quadratic Equations Function Frame

That's it; you have created a working RMI system. Even though you ran the three
consoles on the same computer, RMI uses your network stack and TCP/IP to
communicate between the three separate JVMs. This is a full-fledged RMI system.

7. Alternatives and Discussion


This paper reports on comparisons of Java RMI (such as JDK 1.5.0), SOAP
(such as Apache AXIS2), and CORBA (such as Borland VisiBroker) solutions for
“calculator” example applications. SOAP present another alternative distributed
computing infrastructure; an alternative that is being strongly promoted as preferable
to the use of distributed object middleware such as Java RMI or CORBA.
The analogous mechanisms for generating client and server components for
Java-RMI, SOAP, and CORBA are illustrated in Figure 7.1. When auto generated
client-side stubs are used for SOAP, the development processes and the code
complexity for both client- and server-side are virtually identical for Java-RMI, SOAP,
and CORBA solutions. Typically one starts with an interface definition for the service.
A client-side stub is auto-generated from this interface. On the server side, the
interface is processed to yield a base class for the implementation class that must be
written by the developer. With the mechanisms and costs of development being very
similar, other factors will determine the choice of a technical solution. Systems
developers will have to choose between interoperability where Web Services have

15/27
Developing Calculator application with RMI Edition

advantages, and performance that will favor Java RMI or CORBA.

Java RMI SOAP CORBA


(JDK 1.5.0) (AXIS2) (Borland VisiBroker)

Java Interface WSDL IDL


WSDL processing idl compiler

Implementation Client Server class Client POA


Stub or interface Stub Skeleton
rmic

Client Stub Implementation Implementation

Figure 7.1. Generation of client and server components from interface for
Java-RMI, SOAP, and CORBA

Java RMI and CORBA use optimized connection oriented communications


protocols that are either language specific, or have detailed rules defining how
data-structures and interfaces should be realized. In contrast, SOAP
(application-to-application) are based on the ubiquitous technologies that have grown
up to support WWW-services (human-via browser-to-application). Communications
use HTTP. HTTP is universally supported, and HTTP traffic can normally pass
through firewalls. Tiresome practical details like common data representations are
avoided through the use of textual representations. All numeric and other data are
converted to text. Meta-data, defining structure, are provided in situ as XML mark-up
tags. XML parsers allow client and server implementations to construct their distinct
but equivalent representations of any data structures. The use of HTTP, and XML text
documents, supports increased interoperability but also represents a significant
increase in run-time cost for SOAP solutions as compared with Java-RMI or CORBA
solutions.

Table 7.1. Transferred port comparison of middleware technology using


Java-RMI, SOAP, and CORBA
Technology RMI SOAP CORBA
Java RMI v 1.2 Apache AXIS2
Application Borland VisiBroker
JDK 1.5.0 with Tomcat 5.5
Transferred Port RMI (1099) HTTP (80) Gatekeeper (683)
Firewall Reject Accept Reject

16/27
Developing Calculator application with RMI Edition

7.1 Example services


The “calculator” example services is implemented. They differ mainly in the
type and amount of response data by different technology; one of the efficiency
issues being how well the technologies handle significant data volumes. The
service, “calculator”, actually involves a stateful server. The service defined a
simple four-function (includes addition, subtraction, multiplication, and division)
calculator with operations that each required an integer input argument and
generated an integer response.
The RMI interface for this service is:

Program 8: RMI Calculator Interface


public interface Calculator extends java.rmi.Remote{
public float add(float a, float b) throws java.rmi.RemoteException;
public float sub(float a, float b) throws java.rmi.RemoteException;
public float mul(float a, float b) throws java.rmi.RemoteException;
public float div(float a, float b) throws java.rmi.RemoteException;
}

The IDL interface for this service is:

Program 9: CORBA Calculator IDL


module Calculator {
interface Function {
float add(in float a1, in float b1);
float sub(in float a2, in float b2);
float mul(in float a3, in float b3);
float div(in float a4, in float b4);
};
};

7.2 Client-side stub and client coding


The developer of a Java-RMI client works solely with the remote interface. The
client-side stub class has to be downloaded at run-time from a HTTPserver
co-located with the actual RMI server and the rmiregistry name-server process.
The WSDL for a Web Service must be made available to the developer of the
client-side code. If a UDDI registry were being used, the client developer might

17/27
Developing Calculator application with RMI Edition

be able to download the WSDL from the registry. The Tomcat server
configuration for a JAXRPC implementation can act as an alternative source of
the WSDL. Both .Net and JAXRPC development systems include helper
applications that can generate a client-side stub class, and other helper classes,
from a downloaded WSDL definition.
A CORBA developer has to obtain a copy of the IDL interface definition (this
too could come from a UDDI registry for these are not restricted to handling only
WSDL defined services). The developer then generates a client stub in the
required implementation language via an IDL compiler.
Each test client had code that established a connection and then in a loop
repeatedly invoked service operations. Such tightly coded loops result in client
behavior that is much more demanding than atypical real-world application.
Client application code is essentially identical for all technologies. All
implementations will work with an object reference of the interface type; most of
the code will simply invoke operations via this reference.
A Java-RMI implementation will require a principal server-side object whose
identity is published via the rmiregistry naming service. This could be the
singleton object in a singleton stateless server, or a factory object for a stateful
service. The client obtains a reference via a lookup operation on the naming
service. The underlying Java-RMI runtime arranges to download the stub class
code from an HTTP server as part of the lookup process.
The SOAP uses JAXRPC code to utilize an instance of an auto generated
helper-class to create a stub object (an instance of an application-specific
subclass of a generic Stub class). The end-point URL should be encoded in the
generated stub, but can be overwritten.
A CORBA client might obtain a reference to the service for its stub from a
CosNaming name service, or from a trader, or from a stringified IOR in a file in
a shared file space.

7.3 Result
7.3.1 Costs associated directly with communications
protocols
The typical illustrative Web Service application has a client connect to a
service, submit a single request for data, and terminate. Such applications
are unlikely to put any great demands on either a server host's CPU, or a
communications network; consequently, performance issues are not that
important. In any case, for such applications, Web Services technologies

18/27
Developing Calculator application with RMI Edition

perform well in comparison with the distributed object systems. The data
shown in Table 7.2, Figure 7.2, and Figure 7.3 show relative performances
for three implementations of the “calculator” application with a request for
a single data structure retrieved according to an argument key.
Table 7.2. Costs of single shot request using various technologies
Data Transferred in Number of Connect
Technology Time (Seconds)
Bytes Packets
RMI (Java SE 1.5.0) 0.1829 2885.4 32.1
SOA (AXIS2) 0.6906 2744.9 2
CORBA (VisiBroker) 1.0905 5002 9

Comparison of Middleware Connection Transferred Statement

6000 35

32.1
5002 30
5000

25

Number of Connect Packet


Data Transferred in Bytes

4000

20
2885.4
3000 2744.9
15

2000
10
9

1000
5

2
0 0
CORBA (VisiBroker) RMI (Java SE 1.5.0) SOA (AXIS2)
Data Transferred in Bytes
Middleware Technology
Number of Connect Packet

Figure 7.2. Comparison of Middleware Connection Transferred Statement

Comparison of Middleware Connection Time

1.2
1.0905

0.8
0.6906
Time (Seconds)

0.6

0.4

0.1829
0.2

0
CORBA (VisiBroker) RMI (Java SE 1.5.0) SOA (AXIS2)
Middleware Technology

Figure 7.3. Comparison of Middleware Connection Time

19/27
Developing Calculator application with RMI Edition

7.3.2 Costs of document transfer


Table 7.3, Figure 7.4, and Figure 7.5 show results of traffic analysis for
each of the technologies. These data show the total byte transfers and total
number of packets and are averages of repeated tests.

Table 7.3. Traffic analysis for illustrative applications with different technologies
Data Transferred in Number of Connect
Technology Time
Bytes Packet
RMI (Java SE 1.5.0) 0.817 272128.2 4799.6
SOA (AXIS2) 10.9765 1572026.2 14877.7
CORBA (VisiBroker) 0.7579 276299.5 4013.1

Comparison of Middleware Invocation Transferred Statement

1800000 16000
14877.7
1572026.2
1600000 14000

1400000
12000

Number of Connect Packet


Data Transferred in Bytes

1200000
10000
1000000
8000
800000
6000
600000
4799.6
4013.1 4000
400000
276299.5 272128.2

200000 2000

0 0
CORBA (VisiBroker) RMI (Java SE 1.5.0) SOA (AXIS2)
Data Transferred in Bytes
Middleware Technology
Number of Connect Packet

Figure 7.4. Comparison of Middleware Invocation Time

7.3.3 Common implementation for Java RMI, SOAP, and


CORBA
If a service has heavy internal use on an intranet, and also some external
Internet users, then one possible approach is to use a common
implementation for Java RMI, SOAP, and CORBA services. Clients
establish initial contact with the factory object and use a “create” method to
instantiate a session-server object; the create method returns an
object-reference that the client builds into a stub. It is this object that is
subsequently used via the client's stub and, hopefully, is neatly disposed of
when the client's session is completed.

20/27
Developing Calculator application with RMI Edition

Comparison of Middleware Invocation Time

12
10.9765

10

8
Time (Seconds)

2
0.7579 0.817

0
CORBA (VisiBroker) RMI (Java SE 1.5.0) SOA (AXIS2)
Middleware Technology

Figure 7.5. Comparison of Middleware Invocation Time

Program 10: RMI Calculator Client


public class Client{
public static void main(String[] args){
String result="";
double Received=0,Sent=0,Receiving=0,Sending=0;
double Received2=0,Sent2=0,Receiving2=0,Sending2=0;
/* 初始時間和狀態設定 */
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Received=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sent=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Received2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sent2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
long start = System.currentTimeMillis();
/* connection測試,並擷取時間及網路狀態 */
try{
Calculator cal = (Calculator)
Naming.lookup("rmi://140.113.73.48:1099/CalculatorService");

21/27
Developing Calculator application with RMI Edition

System.out.println("Connection Time: "+(System.currentTimeMillis()-start));


start = System.currentTimeMillis();
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Receiving=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Connection Networking:
"+(Receiving-Received)+"\\"+(Sending-Sent));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Receiving2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Connection Packets:
"+(Receiving2-Received2)+"\\"+(Sending2-Sent2));
/* invocation測試,並擷取時間及網路狀態 */
for(int i=0;i<1000;i++){
System.out.println("Calculator: " + cal.add(1, 1));
}
} catch(Exception e){
System.out.println("Error!");
}
System.out.println("Time: "+(System.currentTimeMillis()-start));
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Receiving=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Networking: "+(Receiving-Received)+"\\"+(Sending-Sent));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Receiving2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Packets: "+(Receiving2-Received2)+"\\"+(Sending2-Sent2));
}
}

22/27
Developing Calculator application with RMI Edition

Program 11: SOAP Calculator Client


public class Client {
public static void main(String[] args) throws Exception {
String result="";
double Received=0,Sent=0,Receiving=0,Sending=0;
double Received2=0,Sent2=0,Receiving2=0,Sending2=0;
/* 初始時間和狀態設定 */
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Received=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sent=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Received2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sent2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
long start = System.currentTimeMillis();
/* connection測試,並擷取時間及網路狀態 */
CalculatorStub stub = new CalculatorStub();
CalculatorStub.Add request = new CalculatorStub.Add();
System.out.println("Connection Time: "+(System.currentTimeMillis()-start));
start = System.currentTimeMillis();
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Receiving=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Connection Networking:
"+(Receiving-Received)+"\\"+(Sending-Sent));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Receiving2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Connection Packets:
"+(Receiving2-Received2)+"\\"+(Sending2-Sent2));
request.setA(1);
request.setB(1);
/* invocation測試,並擷取時間及網路狀態 */

23/27
Developing Calculator application with RMI Edition

for(int i=0;i<1000;i++){
AddResponse response = stub.add(request);
System.out.println("Calculator: " + response.get_return());
}
System.out.println("Time: "+(System.currentTimeMillis()-start));
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Receiving=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Networking: "+(Receiving-Received)+"\\"+(Sending-Sent));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Receiving2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Packets: "+(Receiving2-Received2)+"\\"+(Sending2-Sent2));
}
}

Program 12: CORBA Calculator Client


public class Client {
public static void main(String[] args) {
String result="";
double Received=0,Sent=0,Receiving=0,Sending=0;
double Received2=0,Sent2=0,Receiving2=0,Sending2=0;
/* 初始時間和狀態設定 */
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Received=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sent=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Received2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sent2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
long start = System.currentTimeMillis();
/* connection測試,並擷取時間及網路狀態 */
// Initialize the ORB.

24/27
Developing Calculator application with RMI Edition

org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init(args,null);


// Get the manager Id
byte[] managerId = "Calculator".getBytes();
// Locate an account manager. Give the full POA name and the servant ID.
Calculator.AccountManager manager =
Calculator.AccountManagerHelper.bind(orb, "/calculator_agent_poa",
managerId);
System.out.println("Connection Time: "+(System.currentTimeMillis()-start));
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Receiving=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Connection Networking:
"+(Receiving-Received)+"\\"+(Sending-Sent));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Receiving2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Connection Packets:
"+(Receiving2-Received2)+"\\"+(Sending2-Sent2));
Calculator Function account = manager.open();
start = System.currentTimeMillis();
/* invocation測試,並擷取時間及網路狀態 */
for(int i=0;i<1000;i++){
System.out.println("Calculator: " + account.add(1, 1));
}
System.out.println("Time: "+(System.currentTimeMillis()-start));
result=Execute();
result=result.substring(result.indexOf("Bytes")+5).trim();
Receiving=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));
System.out.println("Networking: "+(Receiving-Received)+"\\"+(Sending-Sent));
result=result.substring(result.indexOf("Unicast packets")+15).trim();
Receiving2=Double.parseDouble(result.substring(0,result.indexOf(" ")));
result=result.substring(result.indexOf(" ")).trim();
Sending2=Double.parseDouble(result.substring(0,result.indexOf("\n")-1));

25/27
Developing Calculator application with RMI Edition

System.out.println("Packets: "+(Receiving2-Received2)+"\\"+(Sending2-Sent2));
}
}

Program 13: Detection of network statement


public static String Execute(){
Process process; //Process可用來執行DOS下的指令
String command="netstat -e",result="";
try {process=Runtime.getRuntime().exec(command);} //執行指令
catch (IOException e) {return "指令發生錯誤!";}
//以下的程式是用來將Stream做轉換,把Stream的資料轉成String輸出
BufferedInputStream inputStream = new BufferedInputStream(process.getInputStream());
byte[] buffer_Data=new byte[256]; //設定緩衝區大小
while(true){
int bytesNRead=0; //讀取輸入串流
try {bytesNRead=inputStream.read(buffer_Data);}
catch (IOException e) {return "無法讀取訊息!";}
if(bytesNRead==-1) break; //若讀取到盡頭則中斷執行
result+=new String(buffer_Data,0,bytesNRead); //寫入資料到string中
}
return result; //回傳結果
}

8. Conclusion
RMI lets Java objects on different hosts communicate with each other in a way
that's similar to how objects running in the same virtual machine communicate with
each other: by calling methods in objects. A remote object lives on a server. Each
remote object implements a remote interface that specifies which of its methods can
be invoked by clients. Clients invoke the methods of the remote object almost exactly
as they invoke local methods. For example, an object running on a local client can
pass a database query as a String argument to a method in a database object running
on a remote server to ask it to sum up a series of records. The server can return the
result to the client as a double.
In this paper, web design and implement the “calculator” example using RMI
which shows in Session 5 and Session 6. We know how to use RMI to build services
automatically. However, in recently, there are many kind of middleware which
include RMI, SOAP, CORBA, COM, DCOM, and so on, and those difference

26/27
Developing Calculator application with RMI Edition

technologies are difference performances. We compare three kind of middleware


which are RMI, SOAP, CORBA to get the best one for services connection and
invocation. RMI

9. References
[1] David Reilly, Michael Reilly, “Java™ Network Programming and Distributed
Computing”, Addison Wesley, 2002.
[2] Elliotte Rusty Harold, “Java Network Programming, 3rd Edition”, O'Reilly, 2004.
[3] František Plášil, Michael Stal, “An Architectural View of Distributed Objects
and Components in CORBA, Java RMI, and COM/DCOM”, Asubmission to
Software Concepts & Tools, 1998.
[4] Jan Graba, “An Introduction to Network Programming with Java”, Springer,
2007.

27/27

Vous aimerez peut-être aussi