ACE+TAO 开源编程笔记/在命名服务上宣传您的服务
外观
所以之前的客户端/服务器对有点笨拙。它们在优雅方面有所欠缺,但在简洁方面有所弥补。这个客户端/服务器示例将展示如何编辑之前的示例,以便它们使用命名服务,不再依赖笨拙的手动 IOR 方法进行寻址。作为旁注,这些 IOR 字符串仅在服务器运行期间有效。由于每个新进程都会生成一个唯一的 IOR 字符串,因此将它们存储在文件中供客户端重用是不可行的,因此,我们使用命名服务,它充当我们服务的 DNS。
因此,要使其正常工作,我们需要获取对命名服务的引用,创建一个用于绑定服务的名称,并将该名称注册到命名服务。以下几行代码是我们需要的
//Now we need a reference to the naming service
Object_var naming_context_object = orb->resolve_initial_references ("NameService");
CosNaming::NamingContext_var naming_context = CosNaming::NamingContext::_narrow (naming_context_object.in ());
//Then initialize a naming context
CosNaming::Name name (1);
name.length (1);
//store the name in the key field...
name[0].id = string_dup ("widgits");
//Then register the context with the nameing service
naming_context->rebind (name, dc_log.in ());
将此代码放在之前服务器的“orb->run”行之上,将其放到命名服务器上。有关完整的源代码,请参见以下列表
因此,如您所见,这里的主要区别是添加了对命名服务的新的包含文件以及上面提到的代码片段。服务器的其他部分保持完全相同。
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream>
#include <cstdlib>
#include "basicI.h"
#include "basicC.h"
#include "ace/streams.h"
#include <orbsvcs/CosNamingC.h>
using namespace std;
using namespace CORBA;
int main (int argc, char* argv[])
{
// First initialize the ORB, that will remove some arguments...
ORB_var orb = ORB_init (argc, argv, "ORB" /* the ORB name, it can be anything! */);
Object_var poa_object = orb->resolve_initial_references ("RootPOA");
PortableServer::POA_var poa = PortableServer::POA::_narrow (poa_object.in ());
PortableServer::POAManager_var poa_manager = poa->the_POAManager ();
poa_manager->activate ();
// Create the servant
My_Factory_i my_factory_i;
// Activate it to obtain the object reference
My_Factory_var my_factory = my_factory_i._this ();
// Put the object reference as an IOR string
String_var ior = orb->object_to_string (my_factory.in ());
//Now we need a reference to the naming service
Object_var naming_context_object = orb->resolve_initial_references ("NameService");
CosNaming::NamingContext_var naming_context = CosNaming::NamingContext::_narrow (naming_context_object.in ());
//Then initialize a naming context
CosNaming::Name name (1);
name.length (1);
//store the name in the key field...
name[0].id = string_dup ("Widgits");
//Then register the context with the nameing service
naming_context->rebind (name, my_factory.in ());
//By default, the following doesn't return unless there is an error
orb->run ();
// Destroy the POA, waiting until the destruction terminates
poa->destroy (1, 1);
orb->destroy ();
return 0;
}