0. 序
这一次我创建一个名为 calc 的 Web Service 程序,功能很简单,实现一个整数 add 函数。
1. 创建源代码
我创建了一个 calc 目录,里面创建下面两个文件:
calc.h:
int ns__add(int x, int y, int &result);
很奇葩的是,函数 add 之前必须加上 ns__,否则后续工作无法继续。看官网的例子,加上 ns2__ 前缀也行。具体什么原因有知道的可以留言补充一下。
calc.cpp
#include "ns.nsmap"
#include "soapService.h" // generated with soapcpp2 -j calc.h
int port = 8080;
int main()
{
Service calc; // service class generated with soapcpp2 -j
calc.soap->accept_timeout = 24*60*60; // quit after 24h of inactivity (optional)
calc.soap->send_timeout = calc.soap->recv_timeout = 5; // max send and receive socket inactivity time (sec)
calc.soap->transfer_timeout = 10; // max time for send or receive of messages (sec)
while (calc.run(port)) // bind, then loop to accept and serve requests
calc.soap_stream_fault(std::cerr);
calc.destroy(); // delete deserialized objects and temp data
return 0;
}
int Service::add(int x, int y, int &result)
{
result = x + y;
return SOAP_OK;
}
代码 Service calc;
,官方的例子中是 Service calc();
但是,这样子用 g++ 编译不过去,因为类的构造函数没参数,不能用空括号。
2. 生成辅助源代码
calc.nsmap
、soapcalcProxy.h
这两个文件是利用程序 soapcpp2
生成的,命令如下:
$ soapcpp2 -j -SL -I/home/jetson/gsoap-2.8/gsoap/import calc.h
** The gSOAP code generator for C and C++, soapcpp2 release 2.8.114
** Copyright (C) 2000-2021, Robert van Engelen, Genivia Inc.
** All Rights Reserved. This product is provided "as is", without any warranty.
** The soapcpp2 tool and its generated software are released under the GPL.
** ----------------------------------------------------------------------------
** A commercial use license is available from Genivia Inc., contact@genivia.com
** ----------------------------------------------------------------------------
Saving soapStub.h annotated copy of the source interface header file
Saving soapH.h serialization functions to #include in projects
Using ns service name: Service
Using ns service style: document
Using ns service encoding: literal
Using ns schema namespace: http://tempuri.org/ns.xsd
Saving ns.wsdl Web Service description
Saving soapService.h service class
Saving soapService.cpp service class
Saving ns.add.req.xml sample SOAP/XML request
Saving ns.add.res.xml sample SOAP/XML response
Saving ns.xsd XML schema
Saving ns.nsmap namespace mapping table
Saving soapC.cpp serialization functions
Compilation successful
3. 编译
输入下面的命令行:
$ g++ -o calc calc.cpp soapC.cpp soapService.cpp stdsoap2.cpp
成功了!
4. 运行服务器
首先运行 calc 程序:
$ ./calc
服务器就运行起来了。
5. 客户端测试
下载了一份 soapUI 客户端测试程序,运行,从菜单选择创建 soap 项目:
其中 Initial WSDL,可以用 Browse 按钮浏览自动生成的 ns.wsdl 文件,结果如下:
点击 Ok。
点击主窗口左上角的 Projects/ns/Service/add/Request 1,
弹出测试窗口。设置服务地址,并把函数 add 参数 x、y 的问号换成具体数值,比如 10 和 20, 点击左上角播放按钮,得到测试结果:
我们看到,右侧结果是 30。
6. 结论
gSoap 官网文档,不知道是在什么机器上测试的,在我的 Jetson Nano 环境下困难重重。经过这一番测试,总算顺利搞定。C/C++ 开发 Web Service 还是不错的。