Hello, gSoap: 用 gSoap 创建自己的第一个 Web Services 程序。

本文详细介绍了如何使用gSOAP库创建一个简单的Web服务。首先,准备项目文件夹并复制必要的库文件。接着,创建源代码包括服务接口定义和实现。然后,通过soapcpp2工具自动生成Web服务所需的源代码。之后,编译项目得到CGI程序hello.cgi。最后,讨论了部署选项,包括在Web服务器上运行或自实现Web服务功能。整个过程涵盖从源代码到部署的完整流程。

1. 准备项目文件夹。

先创建一个文件夹保存我们这个项目的文件。

stdsoap2.cpp 文件从 gSoap 的文件夹里复制到当前文件夹,等一会编译项目的时候要用。其实可以用更优雅的方法,比如设置搜索路径等。本文中,我就粗暴处理了,直接复制过来,当然这样也无伤大雅,

2. 创建源代码

头文件 hello.h

int ns__hello(std::string name, std::string& greeting);

代码文件 hello.cpp

#include "soapH.h"  // include the generated source code headers
#include "ns.nsmap" // include XML namespaces
int main()
{
  return soap_serve(soap_new());
}
int ns__hello(struct soap *soap, std::string name, std::string& greeting)
{
  greeting = "Hello " + name;
  return SOAP_OK;
}

你可能觉得 hello.h 里面竟然没有引用 C++ 头文件 string 就用了 std::string,其实并无影响。因为在代码文件中引用头文件 soapH.h 中会把这些都处理妥当的。

3. 生成 Web Services 源代码

那么代码文件中的 soapH.hns.nsmap 这两个头文件如何得到呢?这个很容易,可以输入命令行 soapcpp2 hello.h 自动生成:

$ soapcpp2 hello.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 ns.hello.req.xml sample SOAP/XML request
Saving ns.hello.res.xml sample SOAP/XML response
Saving ns.xsd XML schema
Saving ns.nsmap namespace mapping table
Saving soapClient.cpp client call stub functions
Saving soapClientLib.cpp client stubs with serializers (use only for libs)
Saving soapServer.cpp server request dispatcher
Saving soapServerLib.cpp server request dispatcher with serializers (use only for libs)
Saving soapC.cpp serialization functions

Compilation successful

4. 编译项目

用下面命令编译生成目标代码 hello.cgi 程序。

g++ -o hello.cgi hello.cpp soapC.cpp soapServer.cpp stdsoap2.cpp

生等片刻,看一下当前文件夹,多出了一个新文件 hello.cgi

5. 部署

这个 cgi 文件,最简单的方法是部署在现成的 Web 服务器里面,比如 Apache 或 IIS 这类软件。

当然,也可以不借助外援,直接用 C 或 C++ 自己实现 Web 服务功能。我喜欢这种方法,回头专门写文章讨论这种方法。

本文没有进行部署,所以测试也就免了。感兴趣的朋友,看我的下一篇文章吧。


参考资料

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

许野平

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值