天天看點

gsoap使用心得!

最近換了個工作環境,現在在大望路這邊上班,呵,剛上班接到的任務就是熟悉gsoap!廢話少說,現在開始gSoap學習!

gSOAP是一個誇平台的,用于開發Web Service服務端和用戶端的工具,在Windows、Linux、MAC OS和UNIX下使用C和C++語言編碼,集合了SSL功能。

下載下傳位址:http://sourceforge.net/projects/gsoap2

官方網站:http://genivia.com/Products/gsoap/index.html

對于Windows平台下開發用戶端,首先下載下傳最新的gsoap_win32_2.7.6c.zip包,具體在以下位址:http://optusnet.dl.sourceforge.net/sourceforge/gsoap2/gsoap_win32_2.7.6c.zip

首先檢視gsoap的User's Guide,基本就能對gsoap有個全面的了解,通過閱讀Sample裡的例子程式深入。然後搜尋網上其它一些文章,比如:

gSOAP簡單多線程伺服器程式 http://blog.chinaunix.net/u1/55091/showart_430965.html

純c gSoap實作WebService            http://hi.baidu.com/2sky2sea/blog/item/40ec5555680279c1b745ae9b.html

接下來我結合自己的實踐與了解,講講VC用gsoap下編寫webService和用戶端程式,有不對的地方還請大家指正,謝謝。

我以網上出現的實作一個簡單的加法函數為例,講講我在操作過程中遇到的問題。

一 伺服器端

1.首先編寫 add.h檔案:

1//gsoap ns service name: add

2//gsoap ns service namespace: http://localhost/add.wsdl

3//gsoap ns service location: http://localhost

4//gsoap ns service executable: add.cgi

5//gsoap ns service encoding: encoded

6//gsoap ns schema namespace: urn:add

7

8int ns__add( int num1, int num2, int* sum );

9

2.用gsoap/bin目錄下的soapcpp2.exe程式,生成一些檔案。可以把soapcpp2.exe拷貝到一add.h目錄下,用cmd執行soapcpp2.exe add.h就可以,在這個目錄下會自動生成許多将來有用的檔案,如add.namap,soapH.h,soapC.cpp,soapClient.cpp,soapServer.cpp等檔案。soapcpp2.exe可以帶參數執行,具體執行soapcpp2.exe -h檢視。

3.建立一個win32控制台工程,加入wsock32.lib庫,将剛才生成的那些檔案添加到工程中。然後編寫webserver.cpp主程式:

#include "add.h"

#include "add.nsmap"

int main(int argc, char* argv[])

{

    int m, s; /**//* master and slave sockets */

    struct soap add_soap;

    soap_init(&add_soap);

    //soap_set_namespaces(&add_soap, add_namespaces);

    if (argc < 2)

    {

        printf("usage: %s <server_port> \n", argv[0]);

        exit(1);

    }

    else

    {

        m = soap_bind(&add_soap, NULL, atoi(argv[1]), 100);

        if (m < 0)

        {

            soap_print_fault(&add_soap, stderr);

            exit(-1);

        }

        fprintf(stderr, "Socket connection successful: master socket = %d\n", m);

        for ( ; ; )

        {

            s = soap_accept(&add_soap);

            if (s < 0)

            {

                soap_print_fault(&add_soap, stderr);

                exit(-1);

            }

            fprintf(stderr, "Socket connection successful: slave socket = %d\n", s);

            soap_serve(&add_soap);//該句說明該server的服務

            soap_end(&add_soap);

    return 0;

}

//server端的實作函數與add.h中聲明的函數相同,但是多了一個目前的soap連接配接的參數

int ns__add(struct soap *add_soap, int num1, int num2, int *sum)

    *sum = num1 + num2;

4. 編譯這個程式,會提示錯誤,将gsoap_win32目錄下stdsoap2.cpp,stdsoap2.h檔案加入工程,重新編譯如果還有錯誤,可能是你将add.h生成的檔案添加入工程出錯的原因。實際上在編寫server程式時,無須帶Client的那些檔案,還有帶Lib的檔案也無須添加到工程中。再重新編譯應該就沒有問題了,啟動4567端口,在ie中輸入localhost:4567,如果顯示xml頁面,說明程式已經啟動。

二 對應的用戶端

1。用戶端程式代碼如下:

#include <stdio.h>

#include <stdlib.h>

#include "soapH.h"

int add(const char* server, int num1, int num2, int *sum);

int main(int argc, char **argv)

    int result = -1;

    char* server="http://localhost:4567";

    int num1 = 0;

    int num2 = 0;

    int sum = 0;

    if( argc < 3 )

        printf("usage: %s num1 num2 \n", argv[0]);

        exit(0);

    num1 = atoi(argv[1]);

    num2 = atoi(argv[2]);

    result = add(server, num1, num2, &sum);

    if (result != 0)

        printf("soap err,errcode = %d\n", result);

        printf("%d+%d=%d\n", num1, num2, sum );

int add( const char* server, int num1, int num2, int *sum )

    int result = 0;

//    soap_set_namespaces(&add_soap, add_namespaces);

    //該函數是用戶端調用的主要函數,後面幾個參數和add.h中聲明的一樣,前面多了3個參數,函數名是接口函數名ns__add前面加上soap_call_

    soap_call_ns__add( &add_soap, server, "", num1, num2, sum );

    if(add_soap.error)

        printf("soap error:%d,%s,%s\n", add_soap.error, *soap_faultcode(&add_soap), *soap_faultstring(&add_soap) );

        result = add_soap.error;

    }

    soap_end(&add_soap);

    soap_done(&add_soap);

    return result;

2.用戶端程式既可以建立一個新的win32控制台程式,将剛才生成的nsmap,soapH.h,soapClient.h等檔案加入工程,編譯既可。我是直接在原先工程中加入一用戶端代碼,将webserver.cpp檔案移除,并且将soapServer.cpp等server端需要的檔案移除,将soapClient.cpp等client端需要的cpp添加到工程,編譯既可。

3.啟動server程式,F5用戶端程式,經測試正常。

三 遇到的問題

1.server端可以編譯成CGI方式執行,而并不是綁定到某個端口,這種方式我沒有實踐。

if (argc < 2) // no args: assume this is a CGI application

   {

      soap_serve(&soap); // serve request, one thread, CGI style

      soap_destroy(&soap); // dealloc C++ data

      soap_end(&soap); // dealloc data and clean up

}2.在編譯伺服器及用戶端程式時一開始對add.h生成的檔案添加到工程,經常出現問題,需要自己不調試。特别是連結時段,server/client要與其生成的檔案相對應,server調用生成的soapserver.cpp,client調用生成的soapclient.cpp檔案。

3.多線程方式,在windows下建議用pthread_win32庫,這裡給出多線程下的例子。

一 gSOAP需要的頭檔案:

//gsoap ns service name: calc

//gsoap ns service style: rpc

//gsoap ns service encoding: encoded

//gsoap ns service namespace: http://127.0.0.1:8089/calc.wsdl

//gsoap ns service location: http://127.0.0.1:8089/cal

//gsoap ns schema  namespace:    urn:calc

int ns__add(double a, double b, double *result);

int ns__sub(double a, double b, double *result);

int ns__mul(double a, double b, double *result);

int ns__div(double a, double b, double *result);

int ns__pow(double a, double b, double *result);

二 多線程伺服器關鍵代碼

#include

#include  "calc.nsmap"

#include  "soapH.h"

/**//////////////////////////////////////////////////////////////////////////

///宏與全局變量的定義

#define  BACKLOG (100) 

#define  MAX_THR (10)  

#define  MAX_QUEUE (1000)

pthread_mutex_t queue_cs;                        //隊列鎖

pthread_cond_t  queue_cv;                          //條件變量

SOAP_SOCKET     queue[MAX_QUEUE];   //數組隊列

int                           head =0, tail =0;          //隊列頭隊列尾初始化        

/**///////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////

void *      process_queue(void *);        //線程入口函數

int         enqueue(SOAP_SOCKET);  //入隊列函數

SOAP_SOCKET dequeue(void);         //出隊列函數

//線程入口函數

void * process_queue(void * soap)

  struct soap * tsoap = (struct soap *)soap;

  for(;;)

  {

        tsoap->socket = dequeue();

        if (!soap_valid_socket(tsoap->socket))

       {

         break;

        soap_serve(tsoap);

        soap_destroy(tsoap);

        soap_end(tsoap);

  }

  return NULL;

//入隊列操作

int enqueue(SOAP_SOCKET sock)

  int status = SOAP_OK;

  int next;

  pthread_mutex_lock(&queue_cs);

  next = tail +1;

  if (next >= MAX_QUEUE)

    next = 0;

  if (next == head)

      status = SOAP_EOM;

  else

    queue[tail] =sock;

    tail = next;

  pthread_cond_signal(&queue_cv);

  pthread_mutex_unlock(&queue_cs);

  return status;

//出隊列操作

SOAP_SOCKET dequeue()

  SOAP_SOCKET sock;

   while (head == tail )

   {

          pthread_cond_wait(&queue_cv,&queue_cs);

   }

  sock = queue[head++];

  if (head >= MAX_QUEUE)

    head =0;

  return sock;

/**///////////////////////////具體服務方法////////////////////////////////////////

//加法的實作

int ns__add(struct soap *soap, double a, double b, double *result)

      *result = a + b;

      return SOAP_OK;

}

//減法的實作

int ns__sub(struct soap *soap, double a, double b, double *result)

{

     *result = a - b;

     return SOAP_OK;

//乘法的實作

int ns__mul(struct soap *soap, double a, double b, double *result)

     *result = a * b;

//除法的實作

int ns__div(struct soap *soap, double a, double b, double *result)

   if (b)

       *result = a / b;

   else

         char *s = (char*)soap_malloc(soap, 1024);

         sprintf(s, "Can't">http://tempuri.org/">Can't divide %f by %f", a, b);

         return soap_sender_fault(soap, "Division by zero", s);

  return SOAP_OK;

//乘方的實作

int ns__pow(struct soap *soap, double a, double b, double *result)

  *result = pow(a, b);

  if (soap_errno == EDOM) /**//* soap_errno 和errorno類似, 但是和widnows相容 */

  {

    char *s = (char*)soap_malloc(soap, 1024);

    sprintf(s, "Can't take the power of %f to  %f", a, b);

    sprintf(s, "Can't">http://tempuri.org/">Can't take power of %f to %f", a, b);

    return soap_sender_fault(soap, "Power function domain error", s);

繼續閱讀