rpc编程示例

参考 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<MAXSTRLEN>; /* 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 <rpc/rpc.h>
#include <time.h>
#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 refused
unable to register (REMTIMEPROG, REMTIMEVERS, udp).

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

 

五。客户端程序  client.c

#include <stdio.h>
#include <rpc/rpc.h>
#include "remtime.h"
#define SERVER "localhost"
int main(void)
{
CLIENT *client; /* client handle - required */
datestr *resstring; /* pointer to a datestr to hold
result */
client = clnt_create(SERVER, REMTIMEPROG, REMTIMEVERS, "tcp");
/* create a client handle to the specified server, program, version
using 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 first
argument is a pointer to void, the second a pointer
to the client handle we wish to use We should really
error check the return! */
printf("%s",*resstring);
return(0);
}

 

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

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

./client
Wed Jan 19 01:56:13 2022

 

------

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

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

 

posted on 2022-01-19 10:02  longbigfish  阅读(306)  评论(0编辑  收藏  举报

导航