Client Example
A client normally interacts with the naming service in the following manner:
It obtains an object reference by resolving the given name (using either resolve_str() or resolve()).
It narrows the object reference returned by the previous step to cast it to the correct type.
It uses the object reference.
Listing 9 and Listing 10 show sample clients in C++ and Java that use the naming service to look up the StockExchange object.
Listing 9: C++ Client Resolving a Name
// C++ ... int main (int argc, char *argv[]) { ... //------------------------------------------------------------------ // The usual initialization boilerplate comes here (not shown). // The following variables are defined by the initialization code: // // 'orbV' - a pointer to the ORB object // // 'namingContextExtV' - a pointer to the root naming context //------------------------------------------------------------------ try { CORBA::Object_var objV; StockExchange_var stockV; objV = rootContextExtV->resolve_str( "London.region/Main.failover/StockExchange" ); stockV = StockExchange::_narrow(objV.in() ); if (CORBA::is_nil(stockV.in() )) { cout << "Nil reference returned for StockExchange object." << endl; return 1; } CORBA::String_var strV = orbV->object_to_string(stockV); cout << strV << endl; // Now make some invocations on the object reference 'StockV' //... } catch (CORBA::UserException& ue) { cerr << ue << endl; return 1; } return 0; }
Listing 10: Java Client Resolving a Name
// Java package Pure.NamesDemo; import Pure.Util.*; import org.omg.CORBA.*; import org.omg.CosNaming.*; import org.omg.CosNaming.NamingContextPackage.*; public class Client { private static ORB m_orb; public static void main(String args[]) { ... //------------------------------------------------------------------ // The usual initialization boilerplate comes here (not shown). // The following variables are defined by the initialization code: // // 'm_orb' - a reference to the ORB object // // 'namingContextExt' - a reference to the root naming context //------------------------------------------------------------------ org.omg.CORBA.Object obj = null; try { // // Resolve the 'StockExchange' object reference // obj = rootContextExt.resolve_str( "London.region/Main.failover/StockExchange" ); StockExchange Stock = StockExchangeHelper.narrow(obj); System.out.println("The 'StockExchange' object reference:"); System.out.println(m_orb.object_to_string(obj) ); // Now make some invocations on the object reference 'Stock' //... } catch (org.omg.CORBA.SystemException ex) { System.err.println(ex); System.exit(1); } catch (org.omg.CORBA.UserException ux) { System.err.println(ux); System.exit(1); } } }
In this example, once the client has the object reference, it stringifies it and prints it to standard output. The client can make remote invocations once it has initialized the object reference.