共用方式為


伺服器應用程式

下列範例來自平臺軟體開發工具包 (SDK) 之 RPC\Hello 目錄中的 'Hello World' 應用程式。 分散式應用程式的伺服器端會通知系統其服務可供使用。 然後,它會等候用戶端要求。 MIDL 編譯程式必須與下列範例搭配使用。

視您的應用程式大小和程式代碼喜好設定而定,您可以選擇在一或多個個別的檔案中實作遠端程式。 在本教學課程程式中,來源檔案 Hellos.c 包含主伺服器例程。 Hellop.c 檔案包含遠端程式。

在個別檔案中組織遠端程式的優點是,程式可以與獨立程序連結,以在程式轉換成分散式應用程式之前偵錯程序代碼。 在獨立程式中執行程序之後,您可以編譯並連結包含遠端程式的來源檔案與伺服器應用程式。 如同用戶端應用程式來源檔案,伺服器應用程式來源檔案必須包含 Hello.h 頭檔。

伺服器會呼叫 RPC 運行時間函式 RpcServerUseProtseqEp,並 RpcServerRegisterIf,讓系結資訊可供用戶端使用。 這個範例程式會將介面句柄名稱傳遞給 RpcServerRegisterIf。 其他參數會設定為 NULL。 然後,伺服器會呼叫 RpcServerListen 函式,指出它正在等候用戶端要求。

伺服器應用程式也必須包含伺服器存根呼叫的兩個記憶體管理功能:midl_user_allocatemidl_user_free。 當遠端程式將參數傳遞至伺服器時,這些函式會在伺服器上配置和釋放記憶體。 在這個範例程式碼中,midl_user_allocatemidl_user_free 只是 C 連結庫函式的包裝函式,mallocfree。 (請注意,在 MIDL 編譯程式產生的正向宣告中,「MIDL」是大寫。頭檔 Rpcndr.h 會將 midl_user_free 和 midl_user_allocate 分別定義為 MIDL_user_free 和 MIDL_user_allocate。)

/* file: hellos.c */
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "hello.h"
#include <windows.h>
#pragma comment(lib, "Rpcrt4.lib")

int main()
{
    RPC_STATUS status;
    unsigned short* pszProtocolSequence = (unsigned short*)L"ncacn_np";
    unsigned short* pszSecurity         = NULL;
    unsigned short* pszEndpoint         = (unsigned short*)L"\\pipe\\hello";
    unsigned int    cMinCalls = 1;
    unsigned int    fDontWait = FALSE;
 
    status = RpcServerUseProtseqEpW(pszProtocolSequence,
                                   RPC_C_LISTEN_MAX_CALLS_DEFAULT,
                                   pszEndpoint,
                                   pszSecurity); 
 
    if (status) exit(status);
 
    status = RpcServerRegisterIf(hello_v1_0_s_ifspec,  
                                 NULL,   
                                 NULL); 
 
    if (status) exit(status);
 
    status = RpcServerListen(cMinCalls,
                             RPC_C_LISTEN_MAX_CALLS_DEFAULT,
                             fDontWait);
 
    if (status) exit(status);
}

void HelloProc(unsigned char * pszString)
{
    printf("%s\n", pszString);
}

/******************************************************/
/*         MIDL allocate and free                     */
/******************************************************/
 
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);
}