基于gsoap开发c++版webservice
gsoap既可以用来做webservice也可以用来做webservice的客户端,其中有两个主要工具soapcpp2.exe和wsdl2h.exe,本文主要简绍开发服务器端:
服务器的开发步骤为:
1、依据规则创建*.h文件
2、使用soapcpp2.exe根据步骤1生成的.h文件创建wsdl文件和服务器所需的其他源文件和头文件
3、编译、运行
客户端的开发步骤为:
1、使用wsdl2h.exe依据wsdl文件生成 "*.h" 文件;
2、使用soapcpp2.exe根据步骤1生成的.h文件创建客户端所需的其他源文件和头文件
案例开发流程如下:
1、依据规则编写"*.h",文件(此处命名为:calculator.h)
//gsoap ns service name: calculate
//gsoap ns service style: rpc
//gsoap ns service namespace: http://192.168.2.102/calculate.wsdl
//gsoap ns service location: http://192.168.2.102/calculate.cgi
//gsoap ns schema namespace: urn:calculate
int ns__add(int num1, int num2, int* result );
int ns__sub(int num1, int num2, int* result );
注意最上面的注释会被soapcpp2.exe程序使用用来构建wsdl文件,所以需要按规定编写,此处服务器端只实现add和sub两个接口。
2、使用soapcpp2.exe根据步骤1生成的.h文件创建wsdl文件和服务器所需的其他源文件和头文件
在命令行中执行:" soapcpp2.exe -S calculator.h " , -S指定只生成服务器端代码,此步骤成功后,会生成编写服务器所需的其他源文件和头文件。
生成的结果有:
创建VS项目将上述生成的头文件和源文件除soapServerLib.cpp和calculator.h外全部添加到项目中,如:
上图中main.cpp是我们手动编写,用来添加main函数和add以及sub接口的实现,如下:
#include "soapH.h"
#include "calculate.nsmap"
#include "stdio.h"
int main(int argc, char *argv[])
{
struct soap *CalculateSoap = soap_new(); //创建一个soap
int iSocket_master = soap_bind(CalculateSoap, NULL, 10000, 100); //绑定到相应的IP地址和端口()NULL指本机,
//10000为端口号,最后一个参数不重要。
if (iSocket_master< 0) //绑定出错
{
soap_print_fault(CalculateSoap, stderr);
exit(-1);
}
printf("SoapBind success,the master socket number is:%d\n", iSocket_master); //绑定成功返回监听套接字
while (1)
{
int iSocket_slaver = soap_accept(CalculateSoap);
if (iSocket_slaver < 0)
{
soap_print_fault(CalculateSoap, stderr);
exit(-2);
}
printf("Get a new connection,the slaver socket number is:%d\n", iSocket_slaver); //绑定成功返回监听套接字
soap_serve(CalculateSoap);
soap_end(CalculateSoap);
}
soap_done(CalculateSoap);
free(CalculateSoap);
return 0;
}
/*加法的具体实现*/
int ns__add(struct soap *soap, int num1, int num2, int* result)
{
if (NULL == result)
{
printf("Error:The third argument should not be NULL!\n");
return SOAP_ERR;
}
else
{
(*result) = num1 + num2;
return SOAP_OK;
}
return SOAP_OK;
}
/*减法的具体实现*/
int ns__sub(struct soap *soap, int num1, int num2, int* result)
{
if (NULL == result)
{
printf("Error:The third argument should not be NULL!\n");
return SOAP_ERR;
}
else
{
(*result) = num1 - num2;
return SOAP_OK;
}
return SOAP_OK;
}
编译并运行项目,在源文件main.cpp中我们指定了端口10000,程序运行中,我们在浏览器中输入"http://192.168.2.102:10000/",可得如下结果:
说明该webservice开发完成,可以使用soapui工具测试服务器提供的add和sub接口。