跳轉到內容

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;
}
華夏公益教科書