一、系統環境
Linux 操作 kernel2.4.2,安裝 gsoap2.6 到目錄/usr/local/gsoap
二、gSOAP 的簡要使用例子
下面是一個簡單的例子,實現一個加法運算的 WebService,具體功能是客戶端(client)輸入 num1 和 num2,服務器端(server)返回 num1 和 num2 相加的結果 sum。
1、首先,我們需要做的是寫一個函數聲明文件,來定義接口函數 ns__add,文件名字為 add.h,內容如下:
//gsoap ns service name: add
//gsoap ns service namespace: http://mail.263.net/add.wsdl
//gsoap ns service location: http://mail.263.net
//gsoap ns service executable: add.cgi
//gsoap ns service encoding: encoded
//gsoap ns schema namespace: urn:add
int ns__add( int num1, int num2, int* sum );
2、然後我們需要創建文件 Makefile,從而利用 gsoapcpp2 工具由 add.h 生成一些 .xml 文件、.c 文件和 .h 文件,這些文件均為自動生成,Makefile的內容如下:
GSOAP_ROOT=/usr/local/gsoap
WSNAME=add
CC=g++ -g -DWITH_NONAMESPACES
INCLUDE=-I $(GSOAP_ROOT)
SERVER_OBJS=$(WSNAME)C.o $(WSNAME)Server.o stdsoap2.o
CLIENT_OBJS=$(GSOAP_ROOT)/env/envC.o $(WSNAME)ClientLib.o stdsoap2.o
ALL_OBJS=${WSNAME}server.o $(WSNAME)C.o $(WSNAME)Server.o ${WSNAME}test.o
${WSNAME}client.o $(WSNAME)ClientLib.o
#總的目標
all:server
${WSNAME}.wsdl:${WSNAME}.h
$(GSOAP_ROOT)/soapcpp2 -p$(WSNAME) -i -n -c ${WSNAME}.h
stdsoap2.o:$(GSOAP_ROOT)/stdsoap2.c
$(CC) -c $?
#編譯一樣生成規則的.o文件
$(ALL_OBJS):%.o:%.c
$(CC) -c $? $(INCLUDE)
#編譯服務器端
server:Makefile ${WSNAME}.wsdl ${WSNAME}server.o $(SERVER_OBJS)
$(CC) ${WSNAME}server.o $(SERVER_OBJS) -o ${WSNAME}server
#編譯客戶端
client:Makefile ${WSNAME}.wsdl ${WSNAME}client.c ${WSNAME}test.c $(ALL_OBJS) stdsoap2.o
$(CC) ${WSNAME}test.o ${WSNAME}client.o $(CLIENT_OBJS) -o ${WSNAME}test
cl:
rm -f *.o *.xml *.a *.wsdl *.nsmap $(WSNAME)H.h $(WSNAME)C.c $(WSNAME)Server.c $(WSNAME)Client.c
$(WSNAME)Stub.* $(WSNAME)$(WSNAME)Proxy.* $(WSNAME)$(WSNAME)Object.* $(WSNAME)ServerLib.c
$(WSNAME)ClientLib.c $(WSNAME)server ns.xsd $(WSNAME)test
3、我們先來做一個 server 端,創建文件 addserver.c 文件,內容如下:
#include "addH.h"
#include "add.nsmap"
int main(int argc, char **argv)
{
int m, s; /* master and slave sockets */
struct soap add_soap;
soap_init(&add_soap);
soap_set_namespaces(&add_soap, add_namespaces);
if (argc < 2)
{
printf("usage: %s\n", argv[0]);
exit(1);
}
else
{
m = soap_bind(&add_soap, NULL, atoi(argv[1]), 100);
if (m < 0)
{
soap_print_fault(&add_soap, stderr);
exit(-1);
}
fprintf(stderr, "Socket connection successful: master socket = %d\n", m);
for ( ; ; )
{
s = soap_accept(&add_soap);
if (s < 0)
{
soap_print_fault(&add_soap, stderr);
exit(-1);
}
fprintf(stderr, "Socket connection successful: slave socket = %d\n", s);
add_serve(&add_soap);//該句說明該server的服務
soap_end(&add_soap);
}
}
return 0;
}
//server端的實現函數與add.h中聲明的函數相同,但是多了一個當前的soap連接的參數
int ns__add(struct soap *add_soap, int num1, int num2, int *sum)
{
*sum = num1 + num2;
return 0;
}
4、讓我們的server跑起來吧:
shell>make
shell>./addserver 8888
如果終端打印出“Socket connection successful: master socket = 3”,那麼你的 server 已經在前台 run 起來了,應該是值得高興的!打開IE,鍵入http://localhost:8888,顯示XML,服務已...〕Socket connection successful: slave socket = 4”,表示服務接收到了一次soap的連接。