C语言 RPC调用 Hello World例子

1、代码

mkdir testcrpc
cd testcrpc
vi test.x

test.x内容,如下

program TESTPROG {
   version VERSION {
     string TEST(string) = 1;
   } = 1;
} = 87654321;

使用rpcgen生成代码

rpcgen test.x

得到文件,如下

test_clnt.c  test.h  test_svc.c

再生成test_clnt_func.c

rpcgen -Sc -o test_clnt_func.c test.x

再生成test_srv_func.c

rpcgen -Ss -o test_srv_func.c test.x

编译服务端程序

gcc -Wall -o test_server  test_srv_func.c test_svc.c

编译客户端程序

gcc -Wall -o test_client test_clnt_func.c test_clnt.c

启动服务端

./test_server

启动客户端

./test_client 127.0.0.1

2、错误解决

错误一

Cannot register service: RPC: Unable to receive; errno = Connection refused

因为没有安装portmap

sudo apt-get install portmap
sudo service portmap start

错误二

Cannot register service: RPC: Authentication error; why = Client credential too weak
unable to register (TESTPROG, VERSION, udp)

解决

sudo -i service portmap stop
sudo -i rpcbind -i -w
sudo -i service portmap start

错误三

这时候启动服务端,在启动客户端,客户端会报下面错误

call failed: RPC: Remote system error

test_clnt_func.c

void
testprog_1(char *host)
{
     CLIENT *clnt;
     char * *result_1;
     char * test_1_arg;

#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 */
}

test_srv_func.c

#include "test.h"
#include <time.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;
}

3、结果

收到消息 ... 服务器当前时间是 :Mon Apr 23 19:03:34 2018

4、参考

以上例子,摘抄自博客:https://blog.csdn.net/hj19870806/article/details/8185604

主要是记录下运行错误。

posted on 2018-04-23 19:43  DaSunWarman  阅读(654)  评论(0编辑  收藏  举报

导航