您的位置:首页 > 编程语言 > C语言/C++

c++实现webservice

2016-03-02 20:46 453 查看
1、编写webservie需要调用的函数,格式如下

(1)对外接口头文件开头注释格式

//gsoap ns service name: scada
//gsoap ns service protocol: SOAP
//gsoap ns service style: rpc
//gsoap ns service location: http://localhost //gsoap ns service executable: scada.cgi
//gsoap ns service encoding: encoded
//gsoap ns schema namespace: urn:scada
前三行是必须有的,如果没有,编译会失败,后四行如果没有gsoap会使用默认的配置进行编译。
//gsoap ns service name: scada,这一行指定了WebService的名字,随意即可,它只关系到最终生成的文件和类的名字,只要符合其实际的含义,名字随意
//gsoap ns service protocol: SOAP ,WebService所用协议,默认SOAP即可
//gsoap ns service style: rpcWebService类型,默认rpc即可,表示使用远程调用
(2)对外接口头文件内容

        声明函数的原型,提供外部调用的接口:
int ns__GetTodayData(int equipid, int valuetype, std::string& result);
int ns__GetStations(std::string& result);
int ns__GetEquips(int stationsid, std::string& result);
注意事项:

a.返回值必须是int

b.函数名必须要以基本命名空间(即上面的ns__)开头,命名空间后面必须要加两个下划线,两个下划线后面就可以跟随任意的符合命名规范的函数名了

c.参数必须至少有1个,最后一个参数表示WebService的返回值,它必须是指针或者引用(因为只有这样我们才能在函数内部修改这个值)

d. 不支持const引用参数,不支持标准库中的容器,如果要使用容器,gsoap-2.8\gsoap\import里面会有对应头文件,使用格式为#import XXX.h

2、下载gsoap-2.8包,解压以后进入gsoap-2.8\gsoap\bin\win32,复制soapcpp2.exe到新建文件夹test

3、cmd命令行切换到test目录,mkdir gSOAP soapcpp2.exe -i -dgSOAP rxscada.h(如果有import头文件,使用-ID:\gsoap-2.8\gsoap的方式指定)。

4、建立工程

(1)创建新工程

用vs2012创建一个普通的空项目,需要导入的文件有:soapC.cpp、soaprxscadaService.cpp、stdsoap2.cpp,soapXXXXXService.cpp的名字会根据接口头文件的注释内容变化而不同,stdsoap2.cpp 在gsoap-2.8\gsoap目录下。

需要放置到项目文件夹内的文件有:



其中stdsoap2.h是从gsoap-2.8\gsoap目录下拷贝的,其他文件都是gsoap2.exe自动生成的

(2)创建接口的实现文件

首先创建一个scadaservice.hpp文件,引入头文件,编写实现的函数体, 其中类名scadaService在soapscadaService.h中定义的。

#include "soapscadaService.h"
#include "scada.nsmap"
#include "soapH.h"
int rxscadaService::GetTodayData(int equipid, int valuetype, std::string& result)
{
if (equipid == 1 && valuetype != 0)
{
result = "{id:1,name:2}";
return SOAP_OK;
} else {
return soap_receiverfault("GetTodayData error:", "please input right paramerter");
}
}

int rxscadaService::GetStations(std::string& result)
{
}

int rxscadaService::GetEquips(int stationsid, std::string& result)
{
}
所有在scada.h里面定义的函数,都必须实现。函数的返回值,如果正常返回SOAP_OK,如果异常,返回soap_receiverfault类型的对象,参数可以根据异常的类型自定义。


(3)创建webservice服务的入口

#include "soapscadaService.h"
#include "scada.h"
#include "scadaservice.hpp"

int main()
{

rxscadaService serv;
serv.recv_timeout = 100;
serv.bind_flags = SO_REUSEADDR;
int _error = SOAP_OK;
std::ofstream _log("soap.log", std::ios::app);

while (true)
{
_error = serv.run(8080);
serv.soap_stream_fault(std::cerr);

serv.soap_stream_fault(_log);
_log.flush();
}
}

其中,_error = serv.run(8080);指定了程序运行的绑定端口号,std::ofstream _log("soap.log",std::ios::app);指定了程序在执行过程中,异常的自动记录文件名。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: