|
NETWORK PROGRAMMING
AND RMI
Computers running on the Internet communicate to
each other using either the Transport Control Protocol (TCP) or the User
Datagram Protocol (UDP), as this diagram illustrates:
|
Application
(HT TP,FTP,Telnet, ....) |
|
Transport
(TCP,UDP,....) |
|
Network
(IP,..) |
|
Link
(Device driver,....) |
When you write Java programs that communicate over
the network, you are programming at the application layer. Typically, you don't
need to concern yourself with the TCP and UDP layers. Instead, you can use the
classes in the java.net package. These classes provide system-independent
network communication. However, to decide which Java classes your programs
should use, you do need to understand how TCP and UDP differ.
TCP: Definition:
TCP (Transport Control Protocol) is a connection-based protocol that
provides a reliable flow of data between two computers.
When two applications want to communicate to each
other reliably, they establish a connection and send data back and forth over
that connection. This is analogous to making a telephone call. (If you want to
speak to Friend, a connection is established when you dial her/him phone number
and s/he answers). You send data back and forth over the connection by speaking
to one another over the phone lines. Like the phone company, TCP guarantees that
data sent from one end of the connection actually gets to the other end and in
the same order it was sent. Otherwise, an error is reported.
TCP provides a point-to-point channel for
applications that require reliable communications. The Hypertext Transfer
Protocol (HT TP), File Transfer Protocol (FTP), and Telnet are all examples of
applications that require a reliable communication channel. The order in which
the data is sent and received over the network is critical to the success of
these applications. When HTTP is used to read from a URL, the data must be
received in the order in which it was sent. Otherwise, you end up with a jumbled
HTML file, a corrupt zip file, or some other invalid information.
UDP:
Definition: UDP (User Datagram Protocol) is
a protocol that sends independent packets of data, called datagrams, from one
computer to another with no guarantees about arrival. UDP is not
connection-based like TCP.
The UDP protocol provides for communication that is
not guaranteed between two applications on the network. UDP is not
connection-based like TCP. Rather, it sends independent packets of data, called
datagrams, from one application to another. Sending datagrams is much like
sending a letter through the postal service: The order of delivery is not
important and is not guaranteed, and each message is independent of any other.
For many applications, the guarantee of reliability
is critical to the success of the transfer of information from one end of the
connection to the other. However, other forms of communication don't require
such strict standards. In fact, they may be slowed down by the extra overhead or
the reliable connection may invalidate the service altogether.
Consider, for example, a clock server that sends
the current time to its client when requested to do so. If the client misses a
packet, it doesn't really make sense to resend it because the time will be
correct when the client receives it on the second try. If the client makes two
requests and receives packets from the server out of order, it doesn't really
matter because the client can figure out that the packets are out of order and
make another request. The reliability of TCP is unnecessary in this instance
because it causes performance degradation and may hinder the usefulness of the
service.
The UDP protocol provides for communication that is
not guaranteed between two applications on the network. UDP is not
connection-based like TCP. Rather, it sends independent packets of data from one
application to another. Sending datagrams is much like sending a letter through
the mail service: The order of delivery is not important and is not guaranteed,
and each message is independent of any others.
Understanding Ports:
Generally speaking, a computer has a single
physical connection to the network. All data destined for a particular computer
arrives through that connection. However, the data may be intended for different
applications running on the computer. So how does the computer know to which
application to forward the data? Through the use of ports.
Data transmitted over the Internet is accompanied
by addressing information that identifies the computer and the port for which it
is destined. The computer is identified by its 32-bit IP address, which IP uses
to deliver data to the right computer on the network. Ports are identified by a
16-bit number, which TCP and UDP use to deliver the data to the right
application.
In connection-based communication such as TCP, a
server application binds a socket to a specific port number. This has the effect
of registering the server with the system to receive all data destined for that
port. A client can then rendezvous with the server at the server's port, as
illustrated here:

The TCP and UDP protocols use ports to map incoming
data to a particular process running on a computer.
In Datagram-based communication such as UDP, the
Datagram packet contains the port number of its destination and UDP routes the
packet to the appropriate application, as illustrated in this figure:

Port numbers range from 0 to 65,535 because
ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023
are restricted; they are reserved for use by well-known services such as HTTP
and FTP and other system services. These ports are called well-known ports. Your
applications should not attempt to bind to them.
Networking Classes
in the JDK:
Through the classes in java.net, Java programs
can use TCP or UDP to communicate over the Internet. The URL, URLConnection,
Socket, and ServerSocket classes all use TCP to communicate over the network.
The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with
UDP.
Working with URL:
One of the most important aspects of the Web is that Tim Berners - Lee devised a
scaleable way to locate all of the resource of the Net. Once you can reliably
name anything and everything, it becomes a very powerful paradigm. The Uniform
Resource Locator (URL) does exactly that. URL is an acronym for Uniform Resource
Locator and is a reference (an address) to a resource on the Internet.
The URL provides a reasonably intelligible form
to uniquely identify or address information on the Internet. URLs are
everywhere; every browser uses them to identify information on the Web. Within
Java's network class library, the URL class provides a simple, concise API to
access information across the Internet using URLs.
What Is an URL?
If you've been surfing the Web, you have
undoubtedly heard the term URL and have used URLs to access HTML pages from the
Web. It's often easiest, although not entirely accurate, to think of a URL as
the name of a file on the World Wide Web because most URLs refer to a file on
some machine on the network. However, remember that URLs also can point to other
resources on the network, such as database queries and command output.
The following is an example of a URL which
addresses the Java Web site hosted by Sun Microsystems:

As in the previous diagram, a URL has two main components:
- Protocol identifier
- Resource name
Note that the protocol identifier and the
resource name are separated by a colon and two forward slashes. The protocol
identifier indicates the name of the protocol to be used to fetch the resource.
The example uses the Hypertext Transfer Protocol (HT TP), which is typically
used to serve up hypertext documents. HT TP is just one of the many different
protocols used to access different types of resources on the net. Other
protocols include File Transfer Protocol (FTP), Gopher, File, and News. The
resource name is the complete address to the resource. The format of the
resource name depends entirely on the protocol used, but for many protocols,
including HT TP, the resource name contains one or more of the components listed
in the following table:
|
Host Name
|
The name of the machine
on which the resource lives. |
|
Filename
|
The pathname to the file
on the machine. |
|
Port Number
|
The port number to which
to connect (typically optional). |
|
Reference
|
A reference to a named
anchor within a resource that usually identifies a
specific location within a file (typically optional). |
For many protocols, the host name and the
filename are required, while the port number and reference are optional. For
example, the resource name for an HTTP URL must specify a server on the network
(Host Name) and the path to the document on that machine (Filename); it also can
specify a port number and a reference. In the URL for the Java Web site
java.sun.com is the host name and the trailing slash is shorthand for the file
named /index.html.
Creating an URL:
The easiest way to create a URL object is from a
String that represents the human-readable form of the URL address. This is
typically the form that another person will use for a URL.
For example,
http://www.ValueNet2000.com/
In
your Java program, you can use a String containing this text to create a URL
object:
URL
gamelan = new URL(" http://www.ValueNet2000.com/");
The URL object created above represents an
absolute URL. An absolute URL contains all of the information necessary to reach
the resource in question. You can also create URL objects from a relative URL
address.
A relative URL contains only enough information
to reach the resource relative to (or in the context of) another URL. Relative
URL specifications are often used within HTML files. For example, suppose you
write an HTML file called RitzHomePage.html. Within this page, are links to
other pages, Picture.html and Myhobby.html, that are on the same machine and in
the same directory as RitzHomePage.. The links to PicturesOfMe.html and
MyKids.html from RitzHomePage.html could be specified just as filenames, like
this:
< a
href=" Picture.html ">Pictures of Me< / a>
< a href=" Myhobby.html ">My Hobbies< / a>
Parsing an URL:
The URL class provides several methods that let you query URL objects. You
can get the protocol, host name, port number, and filename from a URL using
these accessor methods:
|
getProtocol |
Returns the protocol identifier component of the URL.
|
|
getHost |
Returns the host name component of the URL. |
|
GetPort |
Returns the port number component of the URL. The
getPort method returns an integer that is the port number. If the port is
not set, getPort returns -1. |
|
getFile |
Returns the filename component of the URL. |
|
getRef |
Returns the reference component of the URL. |
Reading Directly from an URL:
After you've successfully created a URL, you can call the URL's openStream( )
method to get a stream from which you can read the contents of the URL. The
openStream( ) method returns a java.io.InputStreamapiobject,
so reading from a URL is as easy as reading from an input stream. The following
small Java program uses openStream( ) to get an input stream on the URL http://www.yahoo.com/.
It then opens a BufferedReader on the input stream and reads from the
BufferedReader thereby reading from the URL. Everything read is copied to the
standard output stream:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL
myyahoo = new URL("http://www.yahoo.com/
");
BufferedReader in = new BufferedReader(
new InputStreamReader(myyahoo.openStream( )));
String inputLine;
while ((inputLine = in.readLine( )) != null)
System.out.println(inputLine);
in.close( );
}
}
When you run the program, you should see, scrolling by in your command
window, the HTML commands and textual content from the HTML file located at
http://www.yahoo.com/. Alternatively, the program might hang or you might see an
exception stack trace. If either of the latter two events occurs, you may have
to set the proxy server so that the program can find the Yahoo server.
Connecting to an URL:
After you've successfully created a URL object, you can call the URL object's
openConnection( ) method to connect to it. When you connect to a URL, you are
initializing a communication link between your Java program and the URL over the
network. For example,
import java.net.*;
import java.io.*;
import java.util.Date;
class ConnectionDemo {
int c;
URL hp = new URL("http://www.yahoo.com/");
URLConnection hpCon = np.openConnection( );
System.out.println("Date :"+new Date(hpCon.getDate( )));
System.out.println("Content-type :"+hpCon.getContentType( ));
System.out.println("Expires :"+hpCon.getExpiration( ));
System.out.println("Last - -modified:"+ new Date(hpCon.getLastModified( )));
System.out.println("Content length :"+hpCon.getInputStream( ));
}
If possible, the openConnection( ) method
creates a new URLConnection (if an appropriate one does not already exist),
initializes it, connects to the URL, and returns the URLConnection object. If
something goes wrong--for example, the Yahoo server is down--then the
openConnection method throws an IOException.
Sockets:
A socket is one end-point of a two-way
communication link between two programs running on the network. Socket classes
are used to represent the connection between a client program and a server
program. The java.net package provides two classes--Socket and ServerSocket--that
implement the client side of the connection and the server side of the
connection, respectively.
In Java, you create a socket to establish
connection with the other machine. Then, you get Inputstream and Outputstream
objects from the socket in order to be able to treat the connection as an
IOstream object. There are two stream-based socket classes: a ServerSocket that
a server uses to "listen" for incoming connections and a Socket that a client
uses in order to initiate a connection. Once a client makes a socket connection,
the ServerSocket returns (via the accept( ) method) a corresponding server side
Socket through which direct communications will take place. From then on, you
have a true Socket to Socket connection and you treat both ends the same way
because they are the same. At this point, you use the methods getlnputStream( )
and getOutputStream( ) to produce the corresponding Inputstream and Outputstream
object from each Socket. These must be wrapped inside buffers and formatting
classes just like any other stream object
The following example makes the simplest use of
a Server and a Client using sockets. The Server waits for a Client connection
request. When the Client application connects to the Server, the Server
application sends data to the Client that the Client displays. The Client
application sends data to the Server that the Server displays. Then the
connection between the Client and the Server will be closed. The code is given
below.
// Set up a server that will receive a connection from a client,
// send a message to the client, and close the connection
import java.io.*;
import java.net.*;
import java.awt.*;
import packages.WindowClose;
public class Server extends Frame {
private TextArea display;
public Server( ){
super ("Server") ;
display=new TextArea ("" ,0,0, TextArea.
SCROLLBARS_VERTICAL_ONLY);
add (display, BorderLayout.CENTER);
setSize(300, 250);
setVisible(true) ;
}
public void runServer( ){
ServerSocket server;
Socket connection;
DataInputStream input;
DataOutputStream output;
try{
//Step 1: Create a ServerSocket
server = new ServerSocket(8080);
//Step 2: Wait for a Connection
connection = server.accept( );
display.append ("Connection received from: " +
connection.getInetAddress( ) .
getHostName( )+"\n") ;
//Step 3: Get input and output streams
input = new DataInputStream(connection.
getInputStream( ));
output=new DataOutputStream(connection.
getOutputStream( ));
//Step 4: Process Connection
display.append("Connection Successful \n");
output.writeUTF("Hi, Connection successful") ;
display. append ("Message From Client :" +
input.readUTF() +"\n\n");
//Step 5: Close Connection
display.append("Transmission complete -
Closing socket") ;
connection.close( );
}
catch(IOException e){
e.printStackTrace( ) ;
}
}
public static void main(String args[]){
Server s = new Server( );
s.addWindowListener(new WindowClose( ));
s.runServer( );
}
}
ServerSocket method accept( ) is used to listen for a connection from client
applet or application. Execution of output.writeUTF("Hi, connection
successful"); statement to send the string to the client. Input.readUTF( ) to
read string from the client and display in the TextArea.
// Set up a Client that will read information sent from a Server
// and display the Information
import java.io.*;
import java.net.*;
import java.awt.*;
import packages.WindowClose;
public class Client extends Frame{
private TextArea display;
public Client( ){
super ("Client") ;
}
display=new TextArea ("",0,0, TextArea.
SCROLLBARS-VERTICAL-ONLY);
add (display,BorderLayout.CENTER);
setSize(300, 150) ;
setVisible(true):
}
public void runClient( ){
Socket client;
DatalnputStream input;
DataOutputStream output;
try{
//Step 1: Create a Socket to make Connection.
client = new Socket(InetAddress.getLocalHost( ),
8080);
display.append("Connected to:"+
client.getlnetAddress( ).getHostName( )+ "\n");
//Step 2: Get the input and output streams
input = new DatalnputStream(client.
getlnputStream( ));
output = new DataOutputStream(client.g
etOutputStream( ));
// Step 3: Process connection
display.append("Server message: "+
input.readUTF( )+"\n\n");
output.writeUTF("Thank You");
// Step 4: Close connection
display. append ("Transmission complete -
Closing connection \n");
client.close ( ) ;
}
catch(IOException e){
e.printStackTrace( );
}
}
public static void main(String args[]){
Client c = new Client( );
c.addWindowListener(new WindowClose( ));
c.runClient( );
}
}
client = new Socket(InetAddress.getLocalHost() , 8080)
The above statement instantiates Socket client
with two arguments to the constructor InetAddress.getLocalHost( ) and 8080. The
first argument returns an InetAddress object containing the local host name of
the computer on which this program is executing. The second argument is the port
number on the server. This number must exactly match the port number at which
the server is waiting for connections.
An Overview of RMI
Applications:
The Java Remote Method Invocation (RMI) system
allows an object running in one Java Virtual Machine (VM) to invoke methods on
an object running in another JavaVM. RMI provides for remote communication
between programs written in the Java programming language.
RMI applications are often comprised of two
separate programs: a server and a client. A typical server application creates
some remote objects, makes references to them accessible, and waits for clients
to invoke methods on these remote objects. A typical client application gets a
remote reference to one or more remote objects in the server and then invokes
methods on them. RMI provides the mechanism by which the server and the client
communicate and pass information back and forth. Such an application is
sometimes referred to as a distributed object application.
Distributed object
applications need to
·
Locate remote objects: Applications can use
one of two mechanisms to obtain references to remote objects. An application can
register its remote objects with RMI's simple naming facility, the rmiregistry,
or the application can pass and return remote object references as part of its
normal operation.
·
Communicate with remote objects: Details of
communication between remote objects are handled by RMI; to the programmer,
remote communication looks like a standard Java method invocation.
·
Load class bytecodes for objects that are
passed around: Because RMI allows a caller to pass objects to remote objects,
RMI provides the necessary mechanisms for loading an object's code, as well as
for transmitting its data.
·
The following illustration depicts an RMI
distributed application that uses the registry to obtain a reference to a remote
object. The server calls the registry to associate (or bind) a name with a
remote object. The client looks up the remote object by its name in the server's
registry and then invokes a method on it. The illustration also shows that the
RMI system uses an existing Web server to load class bytecodes, from server to
client and from client to server, for objects when needed.
Advantages of Dynamic
Code Loading:
One of the central and unique features of RMI is
its ability to download the bytecodes (or simply code) of an object's class if
the class is not defined in the receiver's virtual machine. The types and the
behavior of an object, previously available only in a single virtual machine,
can be transmitted to another, possibly remote, virtual machine. RMI passes
objects by their true type, so the behavior of those objects is not changed when
they are sent to another virtual machine. This allows new types to be introduced
into a remote virtual machine, thus extending the behavior of an application
dynamically. The compute engine example in this chapter uses RMI's capability to
introduce new behavior to a distributed program.
Remote Interfaces,
Objects, and Methods:
Like any other application, a distributed
application built using Java RMI is made up of interfaces and classes. The
interfaces define methods, and the classes implement the methods defined in the
interfaces and, perhaps, define additional methods as well. In a distributed
application some of the implementations are assumed to reside in different
virtual machines. Objects that have methods that can be called across virtual
machines are remote objects.
An object becomes remote by implementing a
remote interface, which has the following characteristics.
- A remote interface extends
the interface java.rmi.Remote.
- Each method of the
interface declares java.rmi.RemoteException in its throws clause, in addition
to any application-specific exceptions.
RMI treats a remote object differently from a
non-remote object when the object is passed from one virtual machine to another.
Rather than making a copy of the implementation object in the receiving virtual
machine, RMI passes a remote stub for a remote object. The stub acts as the
local representative, or proxy, for the remote object and basically is, to the
caller, the remote reference. The caller invokes a method on the local stub,
which is responsible for carrying out the method call on the remote object.
A stub for a remote object implements the same
set of remote interfaces that the remote object implements. This allows a stub
to be cast to any of the interfaces that the remote object implements. However,
this also means that only those methods defined in a remote interface are
available to be called in the receiving virtual machine.
Creating Distributed
Applications Using RMI:
When you use RMI to develop a distributed
application, you follow these general steps.
- Design and implement the
components of your distributed application.
- Compile sources and
generate stubs.
- Make classes network
accessible.
- Start the application.
Design and
Implement the Application Components:
First, decide on your application architecture
and determine which components are local objects and which ones should be
remotely accessible. This step includes:
·
Defining the remote interfaces: A remote
interface specifies the methods that can be invoked remotely by a client.
Clients program to remote interfaces, not to the implementation classes of those
interfaces. Part of the design of such interfaces is the determination of any
local objects that will be used as parameters and return values for these
methods; if any of these interfaces or classes does not yet exist; you need to
define them as well.
·
Implementing the remote objects: Remote
objects must implement one or more remote interfaces. The remote object class
may include implementations of other interfaces (either local or remote) and
other methods (which are available only locally). If any local classes are to be
used as parameters or return values to any of these methods, they must be
implemented as well.
·
Implementing the clients: Clients that use
remote objects can be implemented at any time after the remote interfaces are
defined, including after the remote objects have been deployed.
Compile Sources and
Generate Stubs:
This is a two-step process. In the first step
you use the javac compiler to compile the source files, which contain the
implementation of the remote interfaces and implementations, the server classes,
and the client classes. In the second step you use the rmic compiler to create
stubs for the remote objects. RMI uses a remote object's stub class as a proxy
in clients so that clients can communicate with a particular remote object.
Make Classes
Network Accessible:
In this step you make everything--the class
files associated with the remote interfaces, stubs, and other classes that need
to be downloaded to clients--accessible via a Web server.
Start the Application:
Starting the application includes running the
RMI remote object registry, the server, and the client.
Developing RMI
Application:
A working RMI system is composed of the
following parts:
- Interface definitions for
the remote service.
- Implementation of the
remote services.
- Stub and Skeleton files.
- A server to host the remote
services.
- A client program that needs
the remote services.
- An RMI Naming service that
allows clients to find the remote services.
One of the benefits of RMI is transparent
networking. It does not tell you whether the object you are invoking is local or
remote. To do this, RMI needs to somehow simulate a local object that you can
invoke on. This local object is called a stub, and is responsible for accepting
method calls locally and delegating those to actual object implementations.
Similarly, the remote objects need to accept calls from a skeleton that is local
to that remote object.
Steps to build the system:
The following steps can be followed to build your RMI application - (A
calculator)
- Write Java code for the
interface.
- Write Java code for the
implementation class.
- Write Java code for a
remote service host program.
- Develop Java code for an
RMI client program.
- Compile all Java files and
generate Stub and Skeleton class files.
- Run the RMI system.
Calculator Application
in Action:
Write Java code for an interface:
The first step would be to write the required
interface for your application. In RMI, the interface definition will be created
as a Java file. The Calculator interface defines all of the remote features
offered by the service.
public interface Calculator extends java.rmi.Remote {
public long add{long a, long b) throws java.rmi.RemoteException;
public long sub(long a, long b) throws java.rmi.RemoteException;
public long mul(long a, long b) throws java.rmi.RemoteException;
public long div(long a, long b) throws java.rmi.RemoteException;
}
Note that this interface extends Remote, and each method signature declares
that it may throw a RemoteException object.
Write Java code for implementation class:
Once the interface is ready, you will write the implementation for the remote service.
import java.rmi.server.*;
public class CalculatorImpl extends java.rmi.server.
UnicastRemoteObject
implements Calculator {
public CalculatorImpl( ) throws
java.rmi.RemoteException {
super( );
}
public long add(long a, long b)throws
java.rmi.RemoteException {
return a + b;
}
public long sub(long a, long b) throws
java.rmi.RemoteException {
return a -b;
}
public long mul(long a, long b) throws
jaya.rmi.RemoteException {
return a * b;
}
public long div(long a, long b) throws
java.rmi.RemoteException {
return a / b;
}
}
Write Java code for a remote service host program:
import java.rmi.Naming;
public class CalculatorServer {
public CalculatorServer( ) {
try {
Calculator c = new CalculatorImpl( );
Naming.rebind("rmi://90.0.0.40:1099/
CalculatorService", c) ;
}catch (Exception e) {
System. out.println("Trouble Encountered: " + e) ;
}
}
public static void main (String args[])
{
System. out.println("Calculator Server is UP");
new CalculatorServer( );
}
}
The method rebind() takes two parameters, the
URL to the service object, and the local object instance. URL should be given in
the following form:
rmi://[:]/
where the host_name is a name recognized on the
local area network (LAN) or a DNS name on the If it is not specified, rmi uses a
default port 1099.
Develop Java code for RMI
client program:
The client program accepts three user entries,
two numbers, and a mathematical symbol. Based on the symbol passed, the
respective method will be executed from the server to carry out the necessary
calculation. The result will be printed on the screen. The source code for the
client is:
import java.rmi.Naming;
import java.rmi.RemoteException;
import j ava .net. MalformedURLException ;
import java.rmi.NotBoundException;
public class CalculatorClient {
public static void main (String[] arg) {
int numl,num2,result=0;
if (arg.length<3){
System.out.println("Arguments are not passed!!") ;
System.out.print("Syntax:> ") ;
System. out.println ("java CalculatorClient ");
System.exit (0) ;
}
numl = Integer.parseInt(arg[0]);
num2 = Integer.parseInt(arg[l]);
try {
Calculator c = (Calculator);
Naming.lookup("rmi://90.0.0.40/
CalculatorService") ;
if(arg[2].equals("-"))
result =(int) c.sub(numl, num2);
else if(arg[2].equals("+"))
result =(int) c.add(numl, num2);
else if(arg[2] .equals ("x"))
result =(int) c.mul(numl, num2,);
else if(arg[2] .equals ("/"))
result =(int) c.div(numl, num2);
System.out.println("Result:");
System. out.println(numl+" "+arg[2]+" "+num2+" =
"+result);
}
catch (MalformedURLException urlex) {
System.out.println( );
System.out.println("MaIformedURLException");
System.out.printIn(urlex);
}
catch (RemoteException remoteex) {
System.out.println( );
System.out.println("RemoteException");
System.out.println(remoteex);
}
catch (NotBoundException boundex) {
System.out.println( );
System.out.println("NotBoundException");
System.out.println(boundex) ;
}
catch (java.lang.ArithmeticException arithex) {
System.aut.println( );
Sys tem .out.println("java.lang.
ArithmeticException");
System.out.println(arithex);
}
}
}
On the client side, the RMI Registry is accessed
through the static class Naming, It provides the method lookup( ) that a client
uses to query a registry. The method lookup( ) accepts a URL that specifies the
server's host name of the desired service. The method returns a remote reference
to the service object.
rmi://
[:] I
Observe the various types of exceptions that need to be caught while client
processing.
Compile all Java files and generate Stub and Skeleton class files:
Before executing the RMI system you have to compile all the .java files you
have created using the javac compiler. Considering we have created all files in
a folder called RMIDEMO:
C:\RMIDEMO>javac *.java
In order to generate the Stub and Skeleton flies, you must use the RMI
compiler, rmic. The compiler runs on the remote service implementation class
file.
C:\RMIDEMO>rmic CalculatorImpl
After you run rmic, you should locate the files Calculator-Stub.class and
Calculator_Skel.class in your folder.
Run the RMI System:
RMI uses a mechanism to find a remote service; Clients find remote services
by using a naming or directory service. A naming or directory service is run on
a host and a port number. RMI itself includes a simple service called the RMI
Registry .The RMI Registry runs on each machine that hosts remote service
objects and accepts queries for services, by default, on port 1099.
You need to start three consoles (3 MS - DOS Prompt); one for the RMIRegistry,
one for the server, and one for the client.
Start with the Registry program form the directory that contains the classes
you have written.
C:\RMIDEMO>rmiregistry
Once the registry starts running you can switch to the next console. In the
second console, start the server hosting the CalculatorService, and enter the
following:
C:\RMIDEMO>java CalculatorServer
It will start, load the implementation into
memory, and wait for a client connection. Start the client program.
C:\RMIDEMO>java
CalculatorClient 60 60 +
Output will be:
Result:
60 + 60 = 120
You have created a working RMI system. Even
though you run the three consoles on the same computer, RMI uses your network
stack and TCP/IP to communicate between three separate JVMs. This is a
full-fledged RMI system.
HOME
<<PREVIOUS |