共用方式為


建立服務

透過 服務模型 API 和 WsUtil.exe 工具,在 WWSAPI 中建立 Web 服務大幅簡化。 服務模型提供 API,可讓服務和用戶端透過通道傳送和接收訊息做為 C 方法呼叫。 WsUtil 工具會產生用於實作服務的存根和標頭。

使用 WWSAPI 實作計算機服務

使用 Wsutil.exe 工具產生的來源,請依照下列步驟實作服務。

在應用程式來源中包含標頭。

#include "CalculatorProxyStub.h"

實作服務作業。 在此範例中,服務作業是計算機服務的 Add 和 Subtract 函式。

HRESULT CALLBACK Add (const WS_OPERATION_CONTEXT* context, 
                  int a, int b, int* result, 
                  const WS_ASYNC_CONTEXT* asyncContext, 
                  WS_ERROR* error)
{
    *result = a + b;
    printf ("%d + %d = %d\n", a, b, *result);
    return NOERROR;
}

HRESULT CALLBACK Subtract (const WS_OPERATION_CONTEXT* context, 
                  int a, int b, int* result, 
                  const WS_ASYNC_CONTEXT* asyncContext, 
                  WS_ERROR* error)
{
    *result = a - b;
    printf ("%d - %d = %d\n", a, b, *result);
    return NOERROR;
}

藉由設定 WS_SERVICE_CONTRACT 結構的欄位來定義服務合約。

static const DefaultBinding_ICalculatorFunctionTable calculatorFunctions = {Add, Subtract};
static const WS_SERVICE_CONTRACT calculatorContract = 
{
    &DefaultBinding_ICalculatorContractDesc, // comes from the generated header.
    NULL, // for not specifying the default contract
    &calculatorFunctions // specified by the user
};

現在,建立服務主機並加以開啟以進行通訊。

WS_SERVICE_ENDPOINT serviceEndpoint = {0};
serviceEndpoint.uri.chars = L"https://+:80/example"; // address given as uri
serviceEndpoint.binding.channelBinding =  WS_HTTP_CHANNEL_BINDING; // channel binding for the endpoint
serviceEndpoint.channelType = WS_CHANNEL_TYPE_REPLY; // the channel type
serviceEndpoint.uri.length = (ULONG)wcslen(serviceEndpoint.uri.chars);
serviceEndpoint.contract = (WS_SERVICE_CONTRACT*)&calculatorContract;  // the contract
serviceEndpoint.properties = serviceProperties;
serviceEndpoint.propertyCount = WsCountOf(serviceProperties);

if (FAILED (hr = WsCreateServiceHost (&serviceEndpoint, 1, NULL, 0, &host, error)))
    goto Error;

// WsOpenServiceHost  to start the listeners in the service host 
if (FAILED (hr = WsOpenServiceHost (host, NULL, error)))
    goto Error;

如需計算機服務的完整實作,請參閱 HttpCalculatorServiceExample 的程式碼範例。