Linux rpc 編程最簡單實例

通過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.c test_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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章