computer 版 (精华区)
发信人: arbo (arbo), 信区: program
标 题: java笔记13
发信站: 听涛站 (2001年09月17日10:59:47 星期一), 站内信件
The ORB transfers that String back to the client.
标 题: java笔记13
发信站: BBS 水木清华站 (Tue Apr 4 09:34:11 2000)
今天天老师介绍了IDL和Corba.
不过书上没有,所以说的比较简单
IDL 接口定义语言,他是平台,语言无关的。
通过IDL-to-java 或IDL-to-C++ 工具,可以mapping 到相应的语言
IDL 是按照Corba来定义的
看例子吧,没有排版,谁有空帮下忙吧。
The Hello Client-Server Example
This tutorial teaches the basic tasks in building a CORBA distributed applic
atioon using Java IDL. You will build the classic Hello World program as a d
istributed application, with both applet and application clients. The
Hello World program has a single
operation that returns a string to be printed. CORBA terminology and the und
erlyying functionality of the application is discussed in The CORBA Architec
ture. The application diagram is repeated here, along with a review o
ying functionality of the application is discussed in The CORBA Architecture
. T
he application diagram is repeated here, along with a review o
Communication between the client and server.
The client (applet or application) invokes the sayHello operation of the Hel
loSeerver.
The ORB transfers that invocation to the servant object registered for that
IDL interface.
The client prints the value of the String.
Despite its simple design, the Hello World program lets you learn and experi
mentt with all the tasks required to develop almost any CORBA program that u
ses static invocation.
Getting Started
Before you start working with Java IDL, you need two things: version 1.2 of
the JDK software and the idltojava compiler. The JDK provides the API and OR
B needed to enable CORBA-based distributed object interaction. The i
IDL-to-Java mapping to convert IDL interface definitions to corresponding Ja
va iinterfaces, classes, and methods, which you can then use to implement yo
ur client and server code. Click here to download and install the idl
Writing the IDL Interface
This section teaches you how to write a simple IDL interface definition and
how to translate the IDL interface to Java. It also describes the purpose of
each file generated by idltojava compiler.
Developing a Client Application
Learn how to write a simple client application, including how to create an O
RB oobject, how to use the naming service to get an initial object reference
, and how to invoke an operation on a CORBA object.
Developing the Hello World Server
This ction has all the information you need to write a simple IDL server, in
cludding how to create an ORB object for the server, how to instantiate the
servant and connect it to the ORB, how to register the servant with t
make the server wait for invocations on the servant.
Compiling and Running the Hello World Application
After you've written the client and the server, you're ready to compile the
codee and run the programs.
Using Stringified Object References
This section tells you how to make an object reference when there is no nami
ng sservice.
Writing the IDL Interface
In this section, you will write a simple IDL interface for the Hello World p
rogrram. The IDL interface defines the contract between the client and serve
r parts of your application, specifying what operations and attribute
programming-language-independent. You must map it to Java before writing any
of the implementation code. (Running idltojava on the IDL file does this fo
r you automatically.) Here's the complete Hello.idl file.
Writing Hello.idl
OMG IDL is a purely declarative language designed for specifying programming
-lannguage-independent operational interfaces for distributed applications.
OMG specifies a mapping from IDL to several different programming lan
Smalltalk, COBOL, Ada, and Java. When mapped, each statement in OMG IDL is t
ransslated to a corresponding statement in the programming language of choic
e. You can use the tool idltojava to map an IDL interface to Java and
When you map the same IDL to C++ and implement the server in that language,
the Java client and C++ server interoperate through the ORB as though they w
ere written in the same language.
The IDL for Hello World is extremely simple; its single interface has a sing
le ooperation. You need perform only three steps described below.
Step 1: Declaring the CORBA IDL Module
A CORBA module is a namespace that acts as a container for related interface
s annd declarations. It corresponds closely to a Java package. Each module s
tatement in an IDL file is mapped to a Java package statement.
Start your favorite text editor and create a file named Hello.idl.
In your file, enter the module statement:
module HelloApp {
// Add subsequent lines of code here.
};
Save the file. When you run idltojava on the IDL, this statement will genera
te aa package statement in the Java code.
Step 2: Declaring the Interface
Like Java interfaces, CORBA interfaces declare the API contract that an obje
ct hhas with other objects. Each interface statement in the IDL maps to a Ja
va interface statement when mapped.
In your Hello.idl file, enter the interface statement:
module HelloApp {
interface Hello // Add
{ // these
// four
}; // lines.
};
When you compile the IDL, this statement will generate an interface statemen
t inn the Java code. Your client and server classes will implement the Hello
interface in different ways.
Step 3: Declaring the Operations
CORBA operations are the behavior that servers promise to perform on behalf
of cclients that invoke them. Each operation statement in the IDL generates
a corresponding method statement in the generated Java interface.
In your Hello.idl file, enter the operation statement:
module HelloApp {
interface Hello
{
string sayHello(); // Add this line.
};
};
Because our little Hello World application has only a single operation, Hell
o.iddl is now complete.
Mapping Hello.idl from IDL to Java
The tool idltojava reads OMG IDL files and creates the required Java files.
The idltojava defaults are set up so that if you need both client and server
files (as you do for our Hello World program), you simply enter the
IDL file:
Go to a command line prompt.
Change directory to the location of your Hello.idl file.
Enter the compiler command:
idltojava Hello.idl
If you list the contents of the directory, you will see that a directory cal
led HelloApp has been created and that it contains five files. Try opening H
ello.java in your text editor. It looks like this:
/* Hello.java as generated by idltojava */
package HelloApp;
public interface Hello
extends org.omg.CORBA.Object {
String sayHello();
}
With an interface this simple, it is easy to see how the IDL statements map
to tthe generated Java statements.
Mapping of IDL Statements to Java Statements IDL Statement Java Statement
module HelloApp package HelloApp;
interface Hello public interface Hello
string sayHello(); String sayHello();
The single surprising item is the extends statement. All CORBA objects are d
erivved from org.omg.CORBA.Object to ensure required CORBA functionality. Th
e required code is generated by idltojava; you do not need to do any
Understanding the idltojava Compiler Output
The idltojava compiler generates a number of files, based on the options cho
sen on the command line. Because these provide standard functionality, you c
an ignore them until it is time to deploy and run your program. The
idltojava are:
_HelloImplBase.java
This abstract class is the server skeleton, providing basic CORBA functional
ity for the server. It implements the Hello.java interface. The server class
HelloServant extends _HelloImplBase.
_HelloStub.java
This class is the client stub, providing CORBA functionality for the client.
It implements the Hello.java interface.
Hello.java
This interface contains the Java version of our IDL interface. It contains t
he ssingle method sayHello. The Hello.java interface extends org.omg.CORBA.O
bject, providing standard CORBA object functionality as well.
HelloHelper.java
This final class provides auxiliary functionality, notably the narrow method
reqquired to cast CORBA object references to their proper types.
HelloHolder.java
This final class holds a public instance member of type Hello. It provides o
peraations for out and inout arguments, which CORBA has but which do not map
easily to Java's semantics.
When you write the IDL interface, you do all the programming required to gen
eratte all these files for your distributed application. The only additional
work required is the actual implementation of client and server clas
you will create HelloClient.java and HelloApplet.java client classes and the
HellloServer.java class.
Troubleshooting
Error Message: "idltojava" not found
If you try to run idltojava on the file Hello.idl and the system cannot find
idlltojava, it is most likely not in your executable path. Make certain tha
t the location of idltojava is in your path, and try again.
Error Message: preprocessor failed
idltojava uses a C/C++ preprocessor by default. You can change the default b
y seetting two environment variables, CPP and CPPARGS. If you do not want to
use a preprocessor, you can turn it off by adding -fno-cpp to the id
hello.idl
module HelloApp
{
interface Hello
{
string sayHello();
};
};
The Hello Client Server Example
Developing a Client Application
This lesson introduces the basics of writing a CORBA client application. Her
e's the completed version of HelloClient.java.
----------------------------------------------------------------------------
----
Applet Note: While this lesson focuses on writing a CORBA client application
, maany of the steps are identical to those required for writing applets. Th
e major difference is that the applet code appears in the init method
information on how to set up the applet's HTML page, see Setting Up the HTML
Fille (Applets Only). Here's the complete code for the applet version: Hell
oApplet.java.
----------------------------------------------------------------------------
----
Performing Basic Setup
The basic shell of a CORBA client is the same as many Java applications: You
impport required library packages, declare the application class, define a
main method, and remember to handle any exceptions.
Importing Required Packages
Start your text editor and save a new file titled HelloClient.java to your p
rojeect directory.
Import the packages required for the client class:
import HelloApp.*; // The package containing our stubs.
import org.omg.CosNaming.*; // HelloClient will use the naming
// service.
import org.omg.CORBA.*; // All CORBA applications need these
// classes.
----------------------------------------------------------------------------
----
Applet Note: If you are writing an applet, you also need to import java.awt.
Grapphics and org.omg.CosNaming.NamingContextPackage.*. The latter package c
ontains special exceptions thrown by the name service.
----------------------------------------------------------------------------
----
Declaring the Client Class
In HelloClient.java, declare the client class:
public class HelloClient {
// Add the main method here in the next step.
}
----------------------------------------------------------------------------
----
Applet Note: In the applet version of this code, HelloApplet.java, you decla
re tthe applet class like this:
public class HelloApplet extends java.applet.Applet {
// Put the init() method here in the next step.
}
----------------------------------------------------------------------------
----
Defining a main Method
Every Java application needs a main method. Declare it within the scope of t
he HHelloClient class, as follows:
public static void main(String args[]) {
// Put the try-catch block here in the next step.
}
Handling CORBA System Exceptions
Because all CORBA programs can throw CORBA system exceptions at runtime, you
willl place all of the main functionality within a try-catch block. CORBA p
rograms throw system exceptions whenever trouble occurs during any of
invoking the server from the client.
Our exception handler simply prints the name of the exception and its stack
tracce to standard output so you can see what kind of thing has gone wrong.
Inside main, set up a try-catch block:
try {
// Add the rest of the HelloClient code here.
} catch(Exception e) {
System.out.println("ERROR : " + e);
e.printStackTrace(System.out);
}
Creating an ORB Object
A CORBA client needs a local ORB object to perform all of its marshaling and
IIOOP work. Every client instantiates an org.omg.CORBA.ORB object and initi
alizes it by passing to the object certain information about itself.
InsideHelloClient.java's try-catch block, declare and initialize an ORB vari
ablee:
ORB orb = ORB.init(args, null);
The call to the ORB's init method passes in your application's command line
arguuments, allowing you to set certain properties at runtime.
Finding the Hello Server
Once the application has an ORB, it can ask the ORB to locate the actual ser
vicee it needs, in this case the Hello server. There are a number of ways fo
r a CORBA client to get an initial object reference; our client appli
Service specified by OMG and provided with Java IDL. See Using Stringified O
bjecct References for information on how to get an initial object reference
when no naming service is available.
Obtaining the Initial Naming Context
The first step in using the naming service is to get the initial naming cont
ext.. In the try-catch block, below your ORB initialization, call orb.resolv
e_initial_references to get an object reference to the name server:
org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
The string "NameService" is defined for all CORBA ORBs. When you pass in tha
t sttring, the ORB returns the initial naming context, an object reference t
o the name service.
Narrowing the Object Reference
As with all CORBA object references, objRef is a generic CORBA object. To us
e itt as a NamingContext object, you must narrow it to its proper type. Add
the call to narrow just below the previous statement.
NamingContext ncRef = NamingContextHelper.narrow(objRef);
Here we see the use of an idltojava -generated helper class, similar in func
tionn to HelloHelper. The ncRef object is now an org.omg.CosNaming.NamingCon
text and you can use it to access the naming service and find other s
next step.
Finding a Service in Naming
Names can have different structures depending upon the implementation of the
namming service. Consequently, CORBA name servers handle complex names by w
ay of NameComponent objects. Each NameComponent holds a single part,
array of NameComponent objects can hold a fully specified path to an object
on aany computer file or disk system.
To find the Hello server, you first need a NameComponent to hold an identify
ing string for the Hello server. Add this code directly below the call to na
rrow.
NameComponent nc = new NameComponent("Hello", "");
This statement sets the id field of nc, the new NameComponent, to "Hello" an
d thhe kind field to an empty string.
Because the path to the Hello object has just one element, create a single-e
lemeent array out of nc. The NamingContext.resolve method requires this arra
y for its work:
NameComponent path[] = {nc};
Finally, pass path to the naming service's resolve method to get an object r
eferrence to the Hello server and narrow it to a Hello object:
Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
Here you see the HelloHelper helper class at work. The resolve method return
s a generic CORBA object as you saw above when locating the name service its
elf. Therefore, you immediately narrow it to a Hello object, which i
to perform the rest of your work.
Invoking the sayHello Operation
CORBA invocations look like a method call on a local object. The complicatio
ns oof marshaling parameters to the wire, routing them to the server-side OR
B, unmarshaling, and placing the upcall to the server method are comp
programmer. Because so much is done for you by generated code, invocation is
reaally the easiest part of CORBA programming.
Continuing with the try-catch block in HelloClient.java, enter the following
invvocation below the call to the name service's resolvemethod:
String Hello = helloRef.sayHello();
Finally, add code to print the results of the invocation to standard output:
System.out.println(Hello);
Save and close HelloClient.java.
Setting Up the HTML File (Applets Only)
Tutorial.html is provided for displaying your finished applet, but you need
to ccustomize a few attributes and parameters.
Open Tutorial.html in your text editor.
Inside the APPLET tag, enter the path to your project directory as the value
forr the CODEBASE attribute.
In the first PARAM tag, enter the name of the machine where the CORBA name s
erveer runs (most likely your local machine name) as the value for ORBInitia
lHost.
Make sure the second PARAM tag is set to the value of ORBInitialPort that yo
u arre using to run the name server (it's preset to 1050 to work with the de
fault used in the examples in this trail). In any case, it should be
Now you're ready to write the server code.
----------------------------------------------------------------------------
----
The Hello Client Server Example
The Hello Client Server Example
Developing the Hello World Server
This lesson introduces the basics of writing a CORBA transient server. Here'
s thhe complete version of HelloServer.java.
Performing Basic Setup
The structure of a CORBA server program is the same as most Java application
s: YYou import required library packages, declare the server class, define a
main method, and remember to handle any exceptions.
Importing Required Packages
Start your text editor and save a new file titled HelloServer.java. Next, im
portt the packages required for the client class:
// The package containing our stubs.
import HelloApp.*;
// HelloServer will use the naming service.
import org.omg.CosNaming.*;
// The package containing special exceptions thrown by the name // service.
import org.omg.CosNaming.NamingContextPackage.*;
// All CORBA applications need these classes.
import org.omg.CORBA.*;
Declaring the Server Class
Declare the server class:
public class HelloServer {
// Add the main method here in the next step.
}
Defining the main Method
Declare a standard main method:
public static void main(String args[]) {
// Add the try-catch block here in the next step.
}
Handling CORBA System Exceptions
Because all CORBA programs can throw CORBA system exceptions at runtime, you
willl place all of the main functionality within a try-catch block. CORBA p
rograms throw runtime exceptions whenever trouble occurs during any o
unmarshaling, upcall) involved in invocation. The exception handler simply p
rintts the exception and its stack trace to standard output so you can see w
hat kind of thing has gone wrong.
Inside main, set up a try-catch block:
try {
// Add the rest of the HelloServer code here.
} catch(Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}
Creating an ORB Object
Just like a client, a CORBA server also needs a local ORB object. Every serv
er iinstantiates an ORB and registers its servant objects so that the ORB ca
n find the server when it receives an invocation for it.
Inside HelloServer.java's try-catch block, declare and initialize an ORB var
iablle:
ORB orb = ORB.init(args, null);
The call to the ORB's init method passes in the server's command line argume
nts,, allowing you to set certain properties at runtime.
Managing the Servant Object
A server is a process that instantiates one or more servant objects. The ser
vantt implements the interface generated by idltojava and actually performs
the work of the operations on that interface. Our HelloServer needs a
Instantiating the Servant Object
Inside the try-catch block, just below the call to init, instantiate the ser
vantt object:
HelloServant helloRef = new HelloServant();
This servant class isn't defined yet; you will do that in a later step. Next
, coonnect the servant to the ORB, so that the ORB can recognize invocations
on it and pass them along to the correct servant:
orb.connect(helloRef);
Defining the Servant Class
At the end of HelloServer.java, outside the HelloServer class, define the cl
ass for the servant object.
Declare the servant class:
class HelloServant extends _HelloImplBase {
// Add the sayHello method here in the next step.
}
The servant is a subclass of _HelloImplBase so that it inherits the general
CORBBA functionality generated for it by the compiler.
Declare the required sayHello method:
public String sayHello() {
// Add the method implementation here in the next step.
}
Write the sayHello implementation:
return "\nHello World!!\n";
Working with COS Naming
The HelloServer works with the naming service to make the servant object's o
peraations available to clients. The server needs an object reference to the
name service, so that it can register itself and ensure that invocat
routed to its servant object.
Obtaining the Initial Naming Context
In the try-catch block, below instantiation of the servant, call orb.resolve
_iniitial_references to get an object reference to the name server:
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
The string NameService is defined for all CORBA ORBs. When you pass in that
striing, the ORB returns a naming context object that is an object reference
for the name service.
Narrowing the Object Reference
As with all CORBA object references, objRef is a generic CORBA object. To us
e itt as a NamingContext object, you must narrow it to its proper type. Add
the call to narrow just below the previous statement:
NamingContext ncRef = NamingContextHelper.narrow(objRef);
Here you see the use of an idltojava -generated helper class, similar in fun
ctioon to HelloHelper. The ncRef object is now an org.omg.CosNaming.NamingCo
ntext and you can use it to access the naming service and register th
the next step.
Registering the Servant with the Name Server
Just below the call to narrow, create a new NameComponent member:
NameComponent nc = new NameComponent("Hello", "");
This statement sets the id field of nc, the new NameComponent, to "Hello" an
d thhe kind component to the empty string. Because the path to the Hello has
a single element, create the single-element array that NamingContext
NameComponent path[] = {nc};
Finally, pass path and the servant object to the naming service, binding the
serrvant object to the "Hello" id:
ncRef.rebind(path, helloRef);
Now, when the client calls resolve("Hello") on the initial naming context, t
he nnaming service returns an object reference to the Hello servant.
Waiting for Invocation
The server is ready; it simply needs to wait around for a client to request
its service. To achieve that, enter the following code at the end of (but wi
thin) the try-catch block:
java.lang.Object sync = new java.lang.Object();
synchronized(sync) {
sync.wait();
}
This form of Object.wait requires HelloServer to remain alive (though quiesc
ent)) until an invocation comes from the ORB. Because of its placement in ma
in, after an invocation completes and sayHello returns, the server wi
----------------------------------------------------------------------------
----
The Hello Client Server Example
The Hello Client Server Example
Compiling and Running the Hello World Applicatin
Compiling and Running the Hello World Application
By now, you've written the Hello.idl file, run the idltojava compiler on it,
andd you've written the code for the client and server. Your project direct
ory should look something like this:
[PENDING: need new figure now]
----------------------------------------------------------------------------
----
Note to UNIX Users: You should substitute slashes (/) for the backslashes (\
) inn all paths in this document.
----------------------------------------------------------------------------
----
Compiling the Client Application
Compile HelloClient.java:
javac HelloClient.java HelloApp\*.java
Correct any errors in your file and recompile if necessary.
You should see HelloClient.class in the project directory.
Compiling the Server
Compile HelloServer.java:
javac HelloServer.java HelloApp\*.java
Correct any errors in your file and recompile if necessary.
You should see HelloServer.class and HelloServant.class .
Running the Client-Server Application
From an MS-DOS system prompt (Windows) or command shell (UNIX), start the Ja
va IIDL name server:
tnameserv -ORBInitialPort 1050
From a second system prompt or shell, start the Hello server:
java HelloServer -ORBInitialPort 1050
From a third prompt or shell, run the Hello application client:
java HelloClient -ORBInitialPort 1050
The client prints the string from the server to the command line:
Hello world!!
Remember to stop both the NameServer and the HelloServer processes after the
cliient application returns successfully.
Troubleshooting
Specifying ORB Initial Port
The default ORB Initial Port is port 900. If you prefer, you can omit the po
rt sspecifications if you start the name server on port 900. Using Solaris s
oftware, you must become root to start a process on a port under 1024
access before continuing with the tutorial if you choose to use this port fo
r yoour name server.
Class Definition Not Found Error
If the Java compiler (javac) throws a NoClassDefFoundError, try using -cp (c
lassspath) command line option when compiling the source files.
javac -cp . *.java HelloApp\*.java
/blockquote>
----------------------------------------------------------------------------
----
The Hello Client Server Example
The Hello Client Server Example
Using Stringified Object References
To invoke an operation on a CORBA object, a client application needs a refer
encee to the object. You can get such references in a number of ways, such a
s calling ORB.resolve_initial_references or using another CORBA objec
previous lessons, you used both of these methods to get an initial object re
fereence.
Often, however, there is no naming service available in the distributed envi
ronmment. In that situation, CORBA clients use a stringified object referenc
e to find their first object.
In this lesson, you will learn how to create a stringified object reference
as aa part of the server startup, and how the client gets that reference and
destringifies it for use as a real object reference. You can find th
source code: HelloServer.java and HelloStringifiedClient.java.
Making a Stringified Object Reference
For a stringified object reference to be available to the client, the server
musst create the reference and store it somewhere that the client can acces
s. Your reference will be written to disk in the form of a text file.
Copy your existing file HelloStringifiedServer.java.
Because the new server will write a file to disk, you need to add an import
stattement. Add the following:
import java.io.*; // needed for output to the file system.
The new server won't use the naming service, so you don't need the CosNaming
pacckages. Delete these lines from the code:
import org.omg.CosNaming.*; // not needed for stringified
// version
import org.omg.CosNaming.NamingContextPackage.*; // remove
// from code
Delete the code that gets the initial naming context and resolves the refere
nce to a Hello object:
// Get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Bind the object reference in naming
NameComponent nc = new NameComponent("Hello", " ");
NameComponent path[] = {nc};
ncRef.rebind(path, helloRef);
Call the ORB's object_to_string method and pass it the reference to the serv
ant object. This returns the object reference in a string form that can be s
aved in a file on disk.
String ior = orb.object_to_string(helloRef);
Build the path to the file that will be stored, using system properties to d
eterrmine the path structure and syntax.
String filename = System.getProperty("user.home") +
System.getProperty("file.separator")+"HelloIOR";
Use standard Java operations to write the stringified ior to disk:
FileOutputStream fos = new FileOutputStream(filename);
PrintStream ps = new PrintStream(fos);
ps.print(ior);
ps.close();
When HelloStringifiedServer runs, instead of calling the ORB and registering
thee servant object with naming, it creates the text file HelloIOR containi
ng a stringified reference to the servant. The file is stored in your
Getting a Stringified Object Reference
----------------------------------------------------------------------------
----
Note to UNIX users: You should substitute slashes (/) for the backslashes (\
) inn all paths in these steps.
----------------------------------------------------------------------------
----
Copy your existing file HelloStringifiedClient.java.
Because the new client will read a file from the disk, you need to change th
e immport statements. Add the following:
import java.io.*; // needed for input from the file system.
The new client won't use the naming service, so you don't need the CosNaming
pacckage. Delete this line from the code:
import org.omg.CosNaming;*_ // not needed for stringified version
Delete the code that gets the initial naming context and registers the serva
nt wwith the naming service:
// Get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameService");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Resolve the object reference in naming
NameComponent nc = new NameComponent("Hello", " ");
NameComponent path[] = {nc};
Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
Use standard Java operations to read the file that has the object reference.
Notte that client and server programs must know the name of the file and wh
ere it is stored.
String filename = System.getProperty("user.home") +
System.getProperty("file.separator") + "HelloIOR";
FileInputStream fis = new FileInputStream(filename);
DataInputStream dis = new DataInputStream(fis);
String ior = dis.readLine();
The HelloStringifiedClient application now has a String object containing th
e sttringified object reference.
Destringifying the Object Reference
To destringify the object reference in ior, call the standard ORB method:
org.omg.CORBA.Object obj = orb.string_to_object(ior);
Finally, narrow the CORBA object to its proper type, so that the client can
invooke on it:
Hello helloRef = HelloHelper.narrow(obj);
The rest of the client code stays the same.
Compiling a Stringified Hello World
To compile Hello World:
Compile your source code:
javac *.java
Correct any errors in your files and recompile if necessary.
You should see HelloStringifiedServer.class, HelloServant.class, and HelloSt
ringgifiedClient.class in the String directory.
Running a Stringified Hello World
To be certain that you are running your own server, check that all Hello ser
ver and name server processes have been stopped. Stop them if they are runni
ng.
Start the Hello server:
java HelloStringifiedServer -ORBInitialPort 1050 &
Run the Hello application client from another window:
java HelloStringifiedClient -ORBInitialPort 1050
The client prints the string from the server to the command line:
Hello world!!
Remember to stop the HelloStringifiedServer process after the client applica
tionn returns successfully.
----------------------------------------------------------------------------
----
The Hello Client Server Example
idltojava compiler. http://developer.javasoft.com/developer/earlyAccess/jdk1
2/iddltojava.html
/*
* File: ./HelloApp/_HelloImplBase.java
* From: Hello.idl
* Date: Thu Sep 3 09:46:22 1998
* By: idltojava Java IDL 1.2 Nov 12 1997 12:23:47
*/
package HelloApp;
public abstract class _HelloImplBase extends org.omg.CORBA.DynamicImplementa
tionn implements HelloApp.Hello {
// Constructor
public _HelloImplBase() {
super();
}
// Type strings for this class and its superclases
private static final String _type_ids[] = {
"IDL:HelloApp/Hello:1.0"
};
public String[] _ids() { return (String[]) _type_ids.clone(); }
private static java.util.Dictionary _methods = new java.util.Hashtable()
;
static {
_methods.put("sayHello", new java.lang.Integer(0));
}
// DSI Dispatch call
public void invoke(org.omg.CORBA.ServerRequest r) {
switch (((java.lang.Integer) _methods.get(r.op_name())).intValue()) {
case 0: // HelloApp.Hello.sayHello
{
org.omg.CORBA.NVList _list = _orb().create_list(0);
r.params(_list);
String ___result;
___result = this.sayHello();
org.omg.CORBA.Any __result = _orb().create_any();
__result.insert_string(___result);
r.result(__result);
}
break;
default:
throw new org.omg.CORBA.BAD_OPERATION(0, org.omg.CORBA.Complet
ionSStatus.COMPLETED_MAYBE);
}
}
}
/*
* File: ./HelloApp/_HelloStub.java
* From: Hello.idl
* Date: Thu Sep 3 09:46:22 1998
* By: idltojava Java IDL 1.2 Nov 12 1997 12:23:47
*/
package HelloApp;
public class _HelloStub
extends org.omg.CORBA.portable.ObjectImpl
implements HelloApp.Hello {
public _HelloStub(org.omg.CORBA.portable.Delegate d) {
super();
_set_delegate(d);
}
private static final String _type_ids[] = {
"IDL:HelloApp/Hello:1.0"
};
public String[] _ids() { return (String[]) _type_ids.clone(); }
// IDL operations
// Implementation of ::HelloApp::Hello::sayHello
public String sayHello()
{
org.omg.CORBA.Request r = _request("sayHello");
r.set_return_type(org.omg.CORBA.ORB.init().get_primitive_tc(org.o
mg.CCORBA.TCKind.tk_string));
r.invoke();
String __result;
__result = r.return_value().extract_string();
return __result;
}
};
/*
* File: ./HelloApp/Hello.java
* From: Hello.idl
* Date: Thu Sep 3 09:46:22 1998
* By: idltojava Java IDL 1.2 Nov 12 1997 12:23:47
*/
package HelloApp;
public interface Hello
extends org.omg.CORBA.Object {
String sayHello()
;
}
/*
* File: ./HelloApp/HelloHelper.java
* From: Hello.idl
* Date: Thu Sep 3 09:46:22 1998
* By: idltojava Java IDL 1.2 Nov 12 1997 12:23:47
*/
package HelloApp;
public class HelloHelper {
// It is useless to have instances of this class
private HelloHelper() { }
public static void write(org.omg.CORBA.portable.OutputStream out, HelloA
pp.HHello that) {
out.write_Object(that);
}
public static HelloApp.Hello read(org.omg.CORBA.portable.InputStream in)
{
return HelloApp.HelloHelper.narrow(in.read_Object());
}
public static HelloApp.Hello extract(org.omg.CORBA.Any a) {
org.omg.CORBA.portable.InputStream in = a.create_input_stream();
return read(in);
}
public static void insert(org.omg.CORBA.Any a, HelloApp.Hello that) {
org.omg.CORBA.portable.OutputStream out = a.create_output_stream();
write(out, that);
a.read_value(out.create_input_stream(), type());
}
private static org.omg.CORBA.TypeCode _tc;
synchronized public static org.omg.CORBA.TypeCode type() {
if (_tc == null)
_tc = org.omg.CORBA.ORB.init().create_interface_tc(id(), "Hello
");
return _tc;
}
public static String id() {
return "IDL:HelloApp/Hello:1.0";
}
public static HelloApp.Hello narrow(org.omg.CORBA.Object that)
throws org.omg.CORBA.BAD_PARAM {
if (that == null)
return null;
if (that instanceof HelloApp.Hello)
return (HelloApp.Hello) that;
if (!that._is_a(id())) {
throw new org.omg.CORBA.BAD_PARAM();
}
org.omg.CORBA.portable.Delegate dup = ((org.omg.CORBA.portable.Objec
tImppl)that)._get_delegate();
HelloApp.Hello result = new HelloApp._HelloStub(dup);
return result;
}
}
/*
* File: ./HelloApp/HelloHolder.java
* From: Hello.idl
* Date: Thu Sep 3 09:46:22 1998
* By: idltojava Java IDL 1.2 Nov 12 1997 12:23:47
*/
package HelloApp;
public final class HelloHolder
implements org.omg.CORBA.portable.Streamable{
// instance variable
public HelloApp.Hello value;
// constructors
public HelloHolder() {
this(null);
}
public HelloHolder(HelloApp.Hello __arg) {
value = __arg;
}
public void _write(org.omg.CORBA.portable.OutputStream out) {
HelloApp.HelloHelper.write(out, value);
}
public void _read(org.omg.CORBA.portable.InputStream in) {
value = HelloApp.HelloHelper.read(in);
}
public org.omg.CORBA.TypeCode _type() {
return HelloApp.HelloHelper.type();
}
}
// The package containing our stubs.
import HelloApp.*;
// HelloClient will use the naming service.
import org.omg.CosNaming.*;
// The package containing special exceptions thrown by the name service.
import org.omg.CosNaming.NamingContextPackage.*;
// All CORBA applications need these classes.
import org.omg.CORBA.*;
// Needed for the applet.
import java.awt.Graphics;
public class HelloApplet extends java.applet.Applet
{
public void init()
{
try{
// Create and initialize the ORB
ORB orb = ORB.init(this, null);
// Get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameServ
ice"");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Resolve the object reference in naming
NameComponent nc = new NameComponent("Hello", " ");
NameComponent path[] = {nc};
Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
// Call the Hello server object and print the results
message = helloRef.sayHello();
} catch(Exception e) {
System.out.println("HelloApplet exception: " + e);
e.printStackTrace(System.out);
}
}
String message = "";
public void paint(Graphics g)
{
g.drawString(message, 25, 50);
}
}
import HelloApp.*; // The package containing our stubs.
import org.omg.CosNaming.*; // HelloClient will use the naming service.
import org.omg.CORBA.*; // All CORBA applications need these classes.
public class HelloClient
{
public static void main(String args[])
{
try{
// Create and initialize the ORB
ORB orb = ORB.init(args, null);
// Get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameServ
ice"");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Resolve the object reference in naming
NameComponent nc = new NameComponent("Hello", " ");
NameComponent path[] = {nc};
Hello helloRef = HelloHelper.narrow(ncRef.resolve(path));
// Call the Hello server object and print results
String Hello = helloRef.sayHello();
System.out.println(Hello);
} catch(Exception e) {
System.out.println("ERROR : " + e);
e.printStackTrace(System.out);
}
}
}
// The package containing our stubs.
import HelloApp.*;
// HelloServer will use the naming service.
import org.omg.CosNaming.*;
// The package containing special exceptions thrown by the name service.
import org.omg.CosNaming.NamingContextPackage.*;
// All CORBA applications need these classes.
import org.omg.CORBA.*;
public class HelloServer
{
public static void main(String args[])
{
try{
// Create and initialize the ORB
ORB orb = ORB.init(args, null);
// Create the servant and register it with the ORB
HelloServant helloRef = new HelloServant();
orb.connect(helloRef);
// Get the root naming context
org.omg.CORBA.Object objRef = orb.resolve_initial_references("NameServ
ice"");
NamingContext ncRef = NamingContextHelper.narrow(objRef);
// Bind the object reference in naming
NameComponent nc = new NameComponent("Hello", " ");
NameComponent path[] = {nc};
ncRef.rebind(path, helloRef);
// Wait for invocations from clients
java.lang.Object sync = new java.lang.Object();
synchronized(sync){
sync.wait();
}
} catch(Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}
}
}
class HelloServant extends _HelloImplBase
{
public String sayHello()
{
return "\nHello world!!\n";
}
}
// HelloStringifiedClient.java, stringified object reference version
import java.io.*;
import org.omg.CORBA.*;
import HelloApp.*;
public class HelloStringifiedClient
{
public static void main(String args[])
{
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// Get the stringified object reference and destringify it.
String filename = System.getProperty("user.home")+
System.getProperty("file.separator")+"HelloIOR";
FileInputStream fis = new FileInputStream(filename);
DataInputStream dis = new DataInputStream(fis) ;
String ior = dis.readLine() ;
org.omg.CORBA.Object obj = orb.string_to_object(ior) ;
Hello helloRef = HelloHelper.narrow(obj);
// call the Hello server object and print results
String Hello = helloRef.sayHello();
System.out.println(Hello);
} catch (Exception e) {
System.out.println("ERROR : " + e) ;
e.printStackTrace(System.out);
}
}
}
// HelloStringifiedServer.java, stringified object reference version
import java.io.*;
import org.omg.CORBA.*;
import HelloApp.*;
class HelloServant extends _HelloImplBase
{
public String sayHello()
{
return "\nHello world !!\n";
}
}
public class HelloStringifiedServer {
public static void main(String args[])
{
try{
// create and initialize the ORB
ORB orb = ORB.init(args, null);
// create servant and register it with the ORB
HelloServant helloRef = new HelloServant();
orb.connect(helloRef);
// stringify the helloRef and dump it in a file
String str = orb.object_to_string(helloRef);
String filename = System.getProperty("user.home")+
System.getProperty("file.separator")+"HelloIOR";
FileOutputStream fos = new FileOutputStream(filename);
PrintStream ps = new PrintStream(fos);
ps.print(str);
ps.close();
// wait for invocations from clients
java.lang.Object sync = new java.lang.Object();
synchronized (sync) {
sync.wait();
}
} catch (Exception e) {
System.err.println("ERROR: " + e);
e.printStackTrace(System.out);
}
}
}
--
※ 来源:·听涛站 tingtao.dhs.org·[FROM: 匿名天使的家]
Powered by KBS BBS 2.0 (http://dev.kcn.cn)
页面执行时间:4.846毫秒