• 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。

  • 相关阅读:
    [Android] Android 手机下 仿 今日头条 新闻客户端
    [Android] Android Error: Suspicious namespace and prefix combination [NamespaceTypo] when I try create Signed APK
    [Android] Android Build 时报错: java.io.IOException: Could not parse XML from android/accounts/annotations.xml
    Uva 10557 XYZZY
    Uva 705
    Uva532(三维搜索)
    Uva657
    B. Bear and Three Musketeers
    1092 回文字符串(51nod)
    1050 循环数组最大子段和
  • 原文地址:https://www.cnblogs.com/bettersky/p/15821083.html
Copyright © 2020-2023  润新知