您的位置:首页 > 理论基础

如何在本地进程中调用远端计算机上的进程

2007-08-04 09:15 351 查看
回答这个问题其实就是RPC的编程:开发RPC应用程序,一个重要的要素就是接口。显然在客户和服务器的接口存根必须基于完全相同的函数定义上;否则RPC会失败。  
  1.定义接口(HELLO.IDL):  
  [  
          uuid(0EB13191-F7C4-11d3-BF4A-00104B17A4FB),/*注意你必须在自己的程序中生成自己的UUID,利用GUIDGEN应用程序,在VISUAL   STUDIO中*/  
   
          version(1.0)  
  ]  
  2.应用程序配置文件(HELLO.ACF)  
  [  
          implicit_handle(handle_t   hello_IfHandle)  
          //implicit_handle   的使用规定作为全局变量维护句柄  
  ]  
  interface   hello  
  {  
  }  
  3.编译HELLO.IDL  
  MIDL   HELLO.IDL  
  编译的结果生成HELLO_C.C,HELLO_S.C,HELLO.H  
  你看一下这些文件,发现了什么?!  
  4.编写服务器程序  
  #include   <stdlib.h>  
  #include   <stdio.h>  
  #include   "hello.h"  
   
  void   HelloProc(const   unsigned   char*   pszString)  
  {  
  printf("%s/n",pszString);  
  }  
   
  void   Shutdown(void)  
  {  
  RpcMgmtStopServerListening(NULL);  
  RpcServerUnregisterIf(NULL,NULL,FALSE);  
  }  
   
  void   main(int   argc,char*   argv[])  
  {  
  RpcServerUseProtseqEp((unsigned   char   *)"ncacn_ip_tcp",20,(unsigned   char   *)"8000",NULL);  
  RpcServerRegisterIf(hello_v1_0_s_ifspec,NULL,NULL);  
  RpcServerListen(1,20,FALSE);  
  }  
   
  void   __RPC_FAR*   __RPC_USER   midl_user_allocate(size_t   len)  
  {  
  return(malloc(len));  
  }  
   
  void   __RPC_USER   midl_user_free(void   __RPC_FAR   *ptr)  
  {  
  free(ptr);  
  }  
  interface   hello  
  {  
        void   HelloProc([in,string]const   unsigned   char*   pszString);  
        void   Shutdown(void);  
  }  
  5.编译服务器程序  
  CL   HELLOS.C   HELLO_S.C   RPCRT4.LIB  
  生成HELLOS.EXE  
  6.编写客户程序  
  #include   <stdlib.h>  
  #include   <stdio.h>  
  #include   <string.h>  
  #include   "hello.h"  
   
  void   main(int   argc,char*   argv[])  
  {  
  unsigned   char*   pszStringBinding;  
   
  if(argc!=3)  
  {  
  printf("Usage:%s   hostname   string-to-print/n",argv[0]);  
  exit(1);  
  }  
   
  RpcStringBindingCompose(NULL,(unsigned   char*)"ncacn_ip_tcp",(unsigned   char*)argv[1],(unsigned   char*)"8000",NULL,&pszStringBinding);  
  RpcBindingFromStringBinding(pszStringBinding,&hello_IfHandle);  
  if(strcmp(argv[2],"SHUTDOWN"))HelloProc((unsigned   char*)argv[2]);  
  else   Shutdown();  
  RpcStringFree(&pszStringBinding);  
  RpcBindingFree(&hello_IfHandle);  
  exit(0);  
  }  
   
  void   __RPC_FAR*   __RPC_USER   midl_user_allocate(size_t   len)  
  {  
  return(malloc(len));  
  }  
   
  void   __RPC_USER   midl_user_free(void   __RPC_FAR   *ptr)  
  {  
  free(ptr);  
  }  
  7.编译客户程序  
  CL   HELLOC.C   HELLO_C.C   RPCRT4.LIB  
  生成HELLOC.EXE  
  8.测试程序  
  在两个DOS窗口中运行,一个运行HELLOS,在同一台机器上,另一个运行HELLOC   LOCALHOST   “HELLO”  
  看看发生了什么?   
    
   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息