rpc编程示例

您所在的位置:网站首页 rpcinfo安装 rpc编程示例

rpc编程示例

2023-12-10 13:51| 来源: 网络整理| 查看: 265

参考 http://www.cems.uwe.ac.uk/~irjohnso/coursenotes/uqc109/rpcworksheet.pdf

一  定义服务器

/* remtime.x rpc protocol spec for remote time worksheet */const MAXSTRLEN = 80; /* max length of string */typedef string datestr; /* typedef for our ret. val.*/program REMTIMEPROG {

version REMTIMEVERS { datestr GETDATESTR() = 1; } = 1;} = 0x20650609;

使用 rpcgen remtime.x 生成服务器代码

remtime.h  remtime_svc.c  remtime_xdr.c

二  服务代码比如get_data.c

#include #include #include "remtime.h"datestr *getdatestr_1_svc(void *x, struct svc_req *y){ static char buf[MAXSTRLEN]; static char *cp; static datestr *dp; time_t secs; secs = time(NULL); strcpy(buf,ctime(&secs)); cp = buf; dp = &cp; return(dp);}

三 编译服务器

cc  remtime_svc.c  remtime_xdr.c get_data.c -o server

 

四 启动服务器

./server

如果发现 错误 

Cannot register service: RPC: Unable to receive; errno = Connection refusedunable to register (REMTIMEPROG, REMTIMEVERS, udp).

是 rpcinfo 没有装。 安装后就可以启动。 启动后用 rpcinfo  可以看到服务。

 

五。客户端程序  client.c

#include #include #include "remtime.h"#define SERVER "localhost"int main(void){ CLIENT *client; /* client handle - required */ datestr *resstring; /* pointer to a datestr to holdresult */ client = clnt_create(SERVER, REMTIMEPROG, REMTIMEVERS, "tcp");/* create a client handle to the specified server, program, versionusing the specified protocol */

if (client == NULL) { printf("Cannot connect to server\n"); clnt_pcreateerror(SERVER);/* find out why - prints to stdout */ exit(1); } resstring = getdatestr_1(NULL, client);/* as our function receives no arguments our firstargument is a pointer to void, the second a pointerto the client handle we wish to use We should reallyerror check the return! */ printf("%s",*resstring); return(0);}

 

编译 cc -o client remtime_xdr.c remtime_clnt.c remclient.c

启动客户端 ./client 就可以看到打印日期  

./clientWed Jan 19 01:56:13 2022

 

------

这里我们客户端和服务器在同一个节点,所以用 localhost连接服务器。可以在另一个节点上编译client,对应地server地址改为server所在节点的ip。

需要把 remtime_xdr.c remtime_clnt.c  remtime.h 一起拷贝过去编译 client。

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3