Linux rpc 程式設計最簡單例項

2022-05-22 08:24:15 字數 2296 閱讀 4219

通過rpcgen的man手冊看到此工具的作用是把rpc源程式編譯成c語言源程式,從而輕鬆實現遠端過程呼叫。

1.下面的例子程式的作用是客戶端程式(fedora linux下)取中心伺服器也是linux上)時間的,程式設計過程如下:

先編寫乙個 「 rpc 語言 」 ( rpc language ( remote procedure call language ) ) 的原始檔 test.x ,檔案字尾名為 x 。

源**如下:

program testprog = 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.

*/#include

#include "test.h"   

char **

test_1_svc(char **argp, struct svc_req *rqstp)

sprintf(tmp_char, "伺服器當前時間是 :%s", ctime(&rawtime));

result = tmp_char;

return &result;

}再修改客戶端**以顯示伺服器端返回的內容(紅色部分),即修改test_clnt_func.c原始檔,只需要修改其中的函式testprog_1,修改後如下:

void

testprog_1(char *host)

#endif  /* debug */

result_1 = test_1(&test_1_arg, clnt);

if (result_1 == (char **) null)

if (strcmp(*result_1, "error") == 0)

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

參考:

最簡單的socket程式設計

用python做socket程式設計,從實現上來講,是非常簡單的。下面是從他的幫助文件裡面取出來的兩段 顯示了服務端和客戶端。服務端 echo server program import socket host 127.0.0.1 symbolic name meaning the local ho...

C Socket 程式設計簡單例項

c console 程式設計 伺服器端 csharpconsolesokecttestserver.cs using system using system.collections.generic using system.text using system.net using system.net...

Linux Socket程式設計簡單例項

include include include include include include includechar host name 127.0.0.1 int port 7778 struct student t int main if connect socket descriptor,v...