gSoap源码包里面有不少例子,根据里面的例子做一个简单的WebService服务端程序:MyCalcSvr.exe。
用VS创建一个项目:MyCalcSvr,创建Calc.h和CalcSvr.cpp文件,内容如下 :
头文件Calc.h,内容如下:
//gsoap Calc service method-documentation: add Sums two values
int Calc__add(double a, double b, double *result);
//gsoap Calc service method-documentation: sub Subtracts two values
int Calc__sub(double a, double b, double *result);
//gsoap Calc service method-documentation: mul Multiplies two values
int Calc__mul(double a, double b, double *result);
//gsoap Calc service method-documentation: div Divides two values
int Calc__div(double a, double b, double *result);
//gsoap Calc service method-documentation: pow Raises a to b
int Calc__pow(double a, double b, double *result);
程序主文件CalcSvr.cpp,内容如下:
#include "CalcH.h"
#include "Calc.nsmap"
int main(int argc, char **argv)
{
SOAP_SOCKET m, s; /* master and slave sockets */
struct soap soap;
soap_init(&soap);
m = soap_bind(&soap, NULL, 8888, 100);
if (!soap_valid_socket(m))
{
soap_print_fault(&soap, stderr);
exit(-1);
}
fprintf(stderr, "Socket connection successful: master socket = %d/n", m);
for ( ; ; )
{
s = soap_accept(&soap);
fprintf(stderr, "Socket connection successful: slave socket = %d/n", s);
if (!soap_valid_socket(s))
{
soap_print_fault(&soap, stderr);
exit(-1);
}
soap_serve(&soap);
soap_end(&soap);
}
return 0;
}
int Calc__add(struct soap *soap, double a, double b, double *result)
{
*result = a + b;
return SOAP_OK;
}
int Calc__sub(struct soap *soap, double a, double b, double *result)
{
*result = a - b;
return SOAP_OK;
}
int Calc__mul(struct soap *soap, double a, double b, double *result)
{
*result = a * b;
return SOAP_OK;
}
int Calc__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, "<error xmlns=/"http://tempuri.org//">Can't divide %f by %f</error>", a, b);
return soap_sender_fault(soap, "Division by zero", s);
}
return SOAP_OK;
}
int Calc__pow(struct soap *soap, double a, double b, double *result)
{
*result = pow(a, b);
if (soap_errno == EDOM) /* soap_errno is like errno, but compatible with Win32 */
{
char *s = (char*)soap_malloc(soap, 1024);
sprintf(s, "Can't take the power of %f to %f", a, b);
sprintf(s, "<error xmlns=/"http://tempuri.org//">Can't take power of %f to %f</error>", a, b);
return soap_sender_fault(soap, "Power function domain error", s);
}
return SOAP_OK;
}
然后把stdsoap2.h, stdsoap2.cpp, soapcpp2.exe这三个文件拷贝到MyCalcSvr项目目录下面,跟Calc.h文件同一个目录的地方,同时在该目录下创建文件CreateSvr.cmd,文件内容如下:
soapcpp2 -SLwx -pCalc Calc.h
双击运行CreateSvr.cmd,这是将会产生CalcH.h,CalcObject.h,CalcStub.h,CalcServer.cpp,CalcC.cpp,Calc.nsmap这
6个 文件。把 stdsoap2.cpp,CalcServer.cpp,CalcC.cpp这三个文件添加到MyCalcSvr项目中去,编译。
好了,一个简单的WebService程序出炉了。
运行程序,然后 telnet 127.0.01 8888,测试下是否可以连通。