rpcgen

来源:互联网 发布:三国志12全武将数据 编辑:程序博客网 时间:2024/04/29 13:29

通过rpcgen的man手册看到此工具的作用是把RPC源程序编译成C语言源程序,从而轻松实现远程过程调用。
1.下面的例子程序的作用是客户端程序(fedora Linux下)取中心服务器也是Linux上)时间的,编程过程如下:
先编写一个 “ RPC 语言 ” ( RPC Language ( Remote Procedure Call Language ) ) 的源文件 test.x ,文件后缀名为 x 。
源代码如下:
program TESTPROG {
   version VERSION {
     string TEST(string) = 1;
   } = 1;
} = 87654321;

说明:这里数字87654321是RPC程序编号,还有VERSION版本号为1,都是给RPC服务程序用的。同时指定程序接受一个字符串参数。


(1).运行这个命令:
rpcgen test.x

将生成三个源文件:
test_clnt.c  test.h  test_svc.c

 

(2).运行下列命令生成一个客户端源文件test_clnt_func.c:
rpcgen -Sc -o test_clnt_func.c test.x

 

将生成文件:test_clnt_func.c


(3).运行这个命令生成服务端源文件test_srv_func.c:
rpcgen -Ss -o test_srv_func.c test.x

 

将生成文件:test_srv_func.c

 

(4)至此,我们就可以编译生成程序来运行了。
用下面的命令编译生成服务端程序test_server:
gcc -Wall -o test_server test_clnt.ctest_srv_func.c test_svc.c

用下面的命令编译生成客户端程序test_client:
gcc -Wall -o test_client test_clnt_func.c test_clnt.c

运行下列命令启动服务端:
./test_server

运行下列命令可以进行客户端测试:
./test_client 127.0.0.1

但是由于现的的服务端没有处理客户端请求,所以这样的程序还不能完成任何工作(可能会运行错误,我没仔细查找)。
下面我们先给服务端程序加上代码,使这个服务器能完成一定的工作。即修改 test_srv_func.c ,在 “ * insert server code here ”后面加上取时间的代码(红色部分),即修改后的 test_srv_func.c 代码如下:
/*
* This is sample code generated by rpcgen.
* These are only templates and you can use them
* as a guideline for developing your own functions.
http://jiaogen.com
*/
#include <time.h>
#include "test.h"  
char **
test_1_svc(char **argp, struct svc_req *rqstp)
{
        static char * result;
        static char tmp_char[128];
        time_t rawtime;
        /*
         * insert server code here
         */
        if( time(&rawtime) == ((time_t)-1) ) {
                strcpy(tmp_char, "Error");
                result = tmp_char;
                return &result;
        }
        sprintf(tmp_char, "服务器当前时间是 :%s", ctime(&rawtime));
        result = tmp_char;
        return &result;
}

再修改客户端代码以显示服务器端返回的内容(红色部分),即修改test_clnt_func.c源文件,只需要修改其中的函数testprog_1,修改后如下:
void
testprog_1(char *host)
{
        CLIENT *clnt;
        char * *result_1;
        char * test_1_arg;
        test_1_arg = (char *)malloc(128);
#ifndef DEBUG
        clnt = clnt_create (host, TESTPROG, VERSION, "udp");
        if (clnt == NULL) {
                clnt_pcreateerror (host);
                exit (1);
        }
#endif  /* DEBUG */
        result_1 = test_1(&test_1_arg, clnt);
        if (result_1 == (char **) NULL) {
                clnt_perror (clnt, "call failed");
        }
        if (strcmp(*result_1, "Error") == 0) {
                fprintf(stderr, "%s: could not get the time\n", host);
                exit(1);
        }
        printf("收到消息 ... %s\n", *result_1);
#ifndef DEBUG
        clnt_destroy (clnt);
#endif   /* DEBUG */
}

重新运行上述编译命令编译生成程序:
gcc -Wall -o test_server test_clnt.c test_srv_func.c test_svc.c
gcc -Wall -o test_client test_clnt_func.c test_clnt.c

启动服务端程序后运行客户端程序如下:
./test_client 127.0.0.1
收到消息 ... 服务器当前时间是 :Sat Dec 11 15:51:57 2010

0 0
原创粉丝点击