初探 RPC 远程过程调用

简单的跨平台远程调用示例

Posted by Jerry Chen on January 21, 2021

rpclib 库

下载地址:github

官网:rpclib.net

编译方法,编译会生成静态库 rpc.lib 或者 librpc.a:

1
2
3
4
mkdir build
cd build
cmake ..
make

如果需要交叉编译,只需在 CMakeLists.txt 脚本中加入:

建议紧接着 project(xxx) 后面,即下一行;

1
2
set(CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
set(CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)

server

server.cpp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include "rpc/server.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <string>
#include <iostream>

/* 服务器版本 */
#define SERVER_VER "v1.0.2"

/* 获取 system 命令结果 */
std::string getCmdResult(std::string const& strCmd)
{
	char buf[8192] = {0};
	FILE *pf = NULL;
    std::string sResult;
    unsigned int iSize = 0;

#ifdef WIN32
    if (!(pf = _popen(strCmd.c_str(), "r"))) {
#else
    if (!(pf = popen(strCmd.c_str(), "r"))) {
#endif // WIN32
		return "";
	}
 
	while(fgets(buf, sizeof buf, pf)) {
		sResult += buf;
	}
	
#ifdef WIN32
    _pclose(pf);
#else
    pclose(pf);
#endif // WIN32
	
	iSize = sResult.size();
	if(iSize > 0 && sResult[iSize - 1] == '\n'){ /* linux 平台 */
		sResult = sResult.substr(0, iSize - 1);
	}
 
	return sResult;
}

/* 主程序,执行:./server 或 ./server <port> */
int main(int argc, char *argv[])
{
    uint16_t port = rpc::constants::DEFAULT_PORT;

    /* port: argv[1] */
    if(argv[1]){
        if(0 == strcmp("-h", argv[1]) || 0 == strcmp("--help", argv[1])){
            std::cout << "Usage:" << std::endl;
            std::cout << "  [1] ./server" << std::endl;
            std::cout << "  [2] ./server <port>" << std::endl;
            std::cout << "  [3] ./server --help" << std::endl;
            std::cout << "Eg.:" << std::endl;
            std::cout << "  [1] ./server 10069" << std::endl;
            return 0;
        }

        port = atoi(argv[1]);
    }

    /* 创建服务端 */
    rpc::server srv(port);

    /* 系统信息:服务器时间 */
    srv.bind("get_server_time", []() {
        time_t rawtime;
        struct tm *timeinfo;
        time (&rawtime);
        timeinfo = localtime(&rawtime);
        return asctime(timeinfo);
    });

    /* 系统信息:服务器版本 */
    srv.bind("get_server_ver", []() -> std::string {
        return SERVER_VER;
    });

    /* 命令:同步调用远程命令 */
    srv.bind("run_cmd", [](std::string const& cmd) -> std::string {
        return std::string("[remote: " + cmd + "]\r\n") + getCmdResult(cmd);
    });

    /* 命令:异步调用远程命令,调用脚本需要使用该命令 */
    srv.bind("run_async_cmd", [](std::string const& cmd) {
        system((cmd + " &").c_str());
    });

    /* 文件:获取文件大小 */
    srv.bind("run_filelength", [](std::string const& file_path) ->long int {
#ifdef WIN32
        struct _stat file_info;
        _stat(file_path.c_str(), &file_info);
#else
        struct stat file_info;
        stat(file_path.c_str(), &file_info);
#endif // WIN32
        return file_info.st_size;  
    });

    /* 文件:打开文件 */
    srv.bind("run_fopen", [](std::string const& file_path, std::string const& mod) ->long long int {
        return (long long int)fopen(file_path.c_str(), mod.c_str());
    });

    /* 文件:操作文件偏移 */
    srv.bind("run_fseek", [](long long int fp, long int offset, int whence) ->long int {
        if(!(FILE *)fp){
            return -1;
        }

        return (long int)fseek((FILE *)fp, offset, whence);
    });

    /* 文件:写文件 */
    srv.bind("run_fwrite", [](long long int fp, std::vector<unsigned char> const& vbuf) ->long int {
        if(!(FILE *)fp || vbuf.empty()){
            return -1;
        }

        unsigned char *buf = new unsigned char[vbuf.size()];
        memcpy(buf, &vbuf[0], vbuf.size());
        long int write_len = (long int)fwrite(buf, 1, vbuf.size(), (FILE *)fp);
        delete[] buf;
        return write_len;
    });

    /* 文件:写文件(字符串) */
    srv.bind("run_fwrite_str", [](long long int fp, std::string const& str) ->long int {
        if(!(FILE *)fp || str.empty()){
            return -1;
        }

        return (long int)fwrite(str.c_str(), 1, str.length(), (FILE *)fp);
    });

    /* 文件:读文件 */
    srv.bind("run_fread", [](long long int fp, long int len) ->std::vector<unsigned char> {
        std::vector<unsigned char> empty;

        if(!(FILE *)fp || 0 >= len){
            return empty;
        }

        unsigned char *buf = new unsigned char[len];
        long int read_len = (int)fread(buf, 1, len, (FILE *)fp);
        if(0 >= read_len){
            delete[] buf;
            return empty;
        }

        std::vector<unsigned char> vbuf(buf, buf + read_len);
        delete[] buf;
        return vbuf;
    });

    /* 文件:读文件(字符串) */
    srv.bind("run_fread_str", [](long long int fp, long int len) ->std::string {
        if(!(FILE *)fp || 0 >= len){
            return "";
        }

        unsigned char *buf = new unsigned char[len + 1];

        if(0 >= fread(buf, 1, len, (FILE *)fp)){
            delete[] buf;
            return "";
        }

        std::string str((char *)buf);
        delete[] buf;

        return str;
    });

    /* 文件:关闭文件 */
    srv.bind("run_fclose", [](long long int fp) {
        fclose((FILE *)fp);
    });

    /* 服务器开始运行(同步,单线程) */
    std::cout << "RPC server is listening to *:" << port << "." << std::endl;
    srv.run();
    return 0;
}

client

client.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#include "rpc/client.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#ifdef WIN32
#include <Windows.h>
#else
#include <sys/ioctl.h>
#include <unistd.h>
#include <termios.h>
#endif // WIN32

/* 客户端版本 */
#define CLIENT_VER "v1.0.2"

/* 字符进度条打印,输入 进度数值 和 总数值 */
void printf_progress_bar(long int process, long int total)
{
    const char* stat = { "-\\|/" };
    static char buf[102] = { 0, };
    static int last_count = 0;
    int count = 0;
    unsigned short cur_col = 60;

    /* 获取窗口信息 */
#ifdef WIN32
    CONSOLE_SCREEN_BUFFER_INFO info;
    if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info)) {
        cur_col = info.dwSize.X;
    }
#else
    struct winsize cur_size;
    if (0 == ioctl(STDIN_FILENO, TIOCGWINSZ, &cur_size)) {
        cur_col = cur_size.ws_col;
    }
#endif // WIN32

    if(cur_col > 110){
        count = (process * 100) / total;
        if (count < 0) return;
        if (count > 100) count = 100;
        if(count == last_count) return;
        memset(buf, 0, 102);
        memset(buf, '#', count + 1);
        printf("%c[%-101s][%%%d]%c\r", stat[count%4], buf, count, stat[count%4]);
        last_count = count;
    }
    else if(cur_col > 60){
        count = (process * 50) / total;
        if (count < 0) return;
        if (count > 50) count = 50;
        if(count == last_count) return;
        memset(buf, 0, 102);
        memset(buf, '#', count + 1);
        printf("%c[%-51s][%%%d]%c\r", stat[count%4], buf, count * 2, stat[count%4]);
        last_count = count;
    }
    else{
        count = (process * 100) / total;
        if (count < 0) return;
        if (count > 100) count = 100;
        if(count == last_count) return;
        printf("%c[%%%d]%c\r", stat[count%4], count, stat[count%4]);
    }
    last_count = count;
    if(process >= total) printf("\n");
    fflush(stdout);
}

/* 系统信息 */
void get_server_info(rpc::client *c_ptr)
{
    auto server_time = c_ptr->call("get_server_time").as<std::string>();
    auto server_ver = c_ptr->call("get_server_ver").as<std::string>();
    std::cout << "Server time: " << server_time;
    std::cout << "Server version: " << server_ver << std::endl;
}

/* 远程命令 */
void remote_cmd(rpc::client *c_ptr, std::string cmd)
{
    auto cmd_ret = c_ptr->call("run_cmd", cmd.c_str()).as<std::string>();
    std::cout << cmd_ret << std::endl;
}

/* 异步远程命令 */
void remote_async_cmd(rpc::client *c_ptr, std::string cmd)
{
    c_ptr->call("run_async_cmd", cmd.c_str());
    std::cout << "[remote: " + cmd + "] ok\r\n" << std::endl;
}

/* 上传文件 */
int update_file(rpc::client *c_ptr, std::string local_file_path, std::string remote_file_path)
{
    std::cout << "[update] start!" << std::endl;
    /* 打开本地文件 */
    FILE *fp = fopen(local_file_path.c_str(), "rb");
    if(!fp){
        std::cout << "Open local file(" << local_file_path << ") fail!" << std::endl;
        return -1;
    }
    else{
        std::cout << "Open local file(" << local_file_path << ") success!" << std::endl;
    }

    /* 打开远程文件 */
    auto file_ptr = c_ptr->call("run_fopen", remote_file_path.c_str(), "wb").as<long long int>();
    if(!(FILE *)file_ptr){
        std::cout << "Open remote file(" << remote_file_path << ") fail!" << std::endl;
        return -1;
    }
    else{
        std::cout << "Open remote file(" << remote_file_path << ") success!" << std::endl;
    }

    /* 本地文件总大小 */
#ifdef WIN32
    struct _stat local_file_info;
    _stat(local_file_path.c_str(), &local_file_info);
#else
    struct stat local_file_info;
    stat(local_file_path.c_str(), &local_file_info);
#endif // WIN32
    long int local_file_size = local_file_info.st_size;  
    std::cout << "Local file size is " << local_file_size << "!" << std::endl;

    /* 已传文件长度 */
    long int process_len = 0;
    printf_progress_bar(process_len, local_file_size);

    /* 读取本地文件,写入到远程文件 */
    long int read_len;
    unsigned char *buf = new unsigned char[8192];
    while((read_len = fread(buf, 1, 8192, fp)) > 0){
        //std::cout << "Read local len: " << read_len << std::endl;
        /* 写入远程文件 */
        std::vector<unsigned char> vbuf(buf, buf + read_len);
        auto write_len = c_ptr->call("run_fwrite", file_ptr, vbuf).as<long int>();
        //std::cout << "Write remote len: " << write_len << std::endl;

        /* 错误判断 */
        if(write_len != read_len){
            std::cout << "Update failed." << std::endl;
            break;
        }

        /* 打印进度 */
        process_len += write_len;
        printf_progress_bar(process_len, local_file_size);
    }
    delete[] buf;

    /* 关闭远程文件 */
    c_ptr->call("run_fclose", file_ptr);
    std::cout << "Close remote file(" << remote_file_path << ") success!" << std::endl;

    /* 关闭本地文件 */
    fclose(fp);
    std::cout << "Close local file(" << local_file_path << ") success!" << std::endl;

    std::cout << "[update] end!" << std::endl;
    return 0;
}

/* 下载文件 */
int download_file(rpc::client *c_ptr, std::string remote_file_path, std::string local_file_path)
{
    std::cout << "[download] start!" << std::endl;

    /* 打开远程文件 */
    auto file_ptr = c_ptr->call("run_fopen", remote_file_path.c_str(), "rb").as<long long int>();
    if(!(FILE *)file_ptr){
        std::cout << "Open remote file(" << remote_file_path << ") fail!" << std::endl;
        return -1;
    }
    else{
        std::cout << "Open remote file(" << remote_file_path << ") success!" << std::endl;
    }

    /* 打开本地文件 */
    FILE *fp = fopen(local_file_path.c_str(), "wb");
    if(!fp){
        std::cout << "Open local file(" << local_file_path << ") fail!" << std::endl;
        return -1;
    }
    else{
        std::cout << "Open local file(" << local_file_path << ") success!" << std::endl;
    }

    /* 远程文件总大小 */
    auto remote_file_size = c_ptr->call("run_filelength", remote_file_path.c_str()).as<long int>();
    std::cout << "Remote file size is " << remote_file_size << "!" << std::endl;

    /* 已传文件长度 */
    long int process_len = 0;
    printf_progress_bar(process_len, remote_file_size);

    /* 读取远程文件,写入到本地文件 */
    unsigned char *buf = new unsigned char[8192];
    while(1){
        auto read_vbuf = c_ptr->call("run_fread", file_ptr, 8192).as<std::vector<unsigned char>>();
        if(read_vbuf.size() > 0){
            //std::cout << "Read remote len: " << read_vbuf.size() << std::endl;
            memcpy(buf, &read_vbuf[0], read_vbuf.size());
            long int write_len = fwrite(buf, 1, read_vbuf.size(), fp);
            //std::cout << "Write local len: " << write_len << std::endl;

            /* 错误判断 */
            if(write_len != read_vbuf.size()){
                std::cout << "Download failed." << std::endl;
                break;
            }

            /* 打印进度 */
            process_len += write_len;
            printf_progress_bar(process_len, remote_file_size);
        }
        else{
            break;
        }
    }
    delete[] buf;

    /* 关闭本地文件 */
    fclose(fp);
    std::cout << "Close local file(" << local_file_path << ") success!" << std::endl;

    /* 关闭远程文件 */
    c_ptr->call("run_fclose", file_ptr);
    std::cout << "Close remote file(" << remote_file_path << ") success!" << std::endl;

    std::cout << "[download] end!" << std::endl;
    return 0;
}

/* 判断 IP 是否合法 */
bool isIPAddressValid(const char* pszIPAddr)  
{  
    if (!pszIPAddr) return false; //若pszIPAddr为空  
    char IP1[100],cIP[4];  
    int len = strlen(pszIPAddr);  
    int i = 0,j=len-1;  
    int k, m = 0,n=0,num=0;  
    //去除首尾空格(取出从i-1到j+1之间的字符):  
    while (pszIPAddr[i++] == ' ');  
    while (pszIPAddr[j--] == ' ');  
      
    for (k = i-1; k <= j+1; k++)  
    {  
        IP1[m++] = *(pszIPAddr + k);  
    }       
    IP1[m] = '\0';  
      
    char *p = IP1;  
  
    while (*p!= '\0')  
    {  
        if (*p == ' ' || *p<'0' || *p>'9') return false;  
        cIP[n++] = *p; //保存每个子段的第一个字符,用于之后判断该子段是否为0开头  
  
        int sum = 0;  //sum为每一子段的数值,应在0到255之间  
        while (*p != '.'&&*p != '\0')  
        {  
          if (*p == ' ' || *p<'0' || *p>'9') return false;  
          sum = sum * 10 + *p-48;  //每一子段字符串转化为整数  
          p++;  
        }  
        if (*p == '.') {  
            if ((*(p - 1) >= '0'&&*(p - 1) <= '9') && (*(p + 1) >= '0'&&*(p + 1) <= '9'))//判断"."前后是否有数字,若无,则为无效IP,如“1.1.127.”  
                num++;  //记录“.”出现的次数,不能大于3  
            else  
                return false;  
        };  
        if ((sum > 255) || (sum > 0 && cIP[0] =='0')||num>3) return false;//若子段的值>255或为0开头的非0子段或“.”的数目>3,则为无效IP  
  
        if (*p != '\0') p++;  
        n = 0;  
    }  
    if (num != 3) return false;  
    return true;  
}

/* 主程序 */
int main(int argc, char *argv[])
{
    uint16_t port = rpc::constants::DEFAULT_PORT;

    /* port: argv[1] */
    if(!argv[1] || 0 == strcmp("-h", argv[1]) || 0 == strcmp("--help", argv[1])){
        std::cout << "Version: " << CLIENT_VER << std::endl;
        std::cout << "Usage:" << std::endl;
        std::cout << "  [1] ./client <servet_ip:port>" << std::endl;
        std::cout << "  [2] ./client <servet_ip:port> info" << std::endl;
        std::cout << "  [3] ./client <servet_ip:port> cmd xxx1 xxx2 ..." << std::endl;
        std::cout << "  [4] ./client <servet_ip:port> async_cmd xxx.sh xxx1 xxx2 ..." << std::endl;
        std::cout << "  [5] ./client <servet_ip:port> update local_file remote_file" << std::endl;
        std::cout << "  [6] ./client <servet_ip:port> download remote_file local_file" << std::endl;
        std::cout << "  [7] ./client --help" << std::endl;
        std::cout << "Eg.:" << std::endl;
        std::cout << "  [1] ./client 127.0.0.1:10069" << std::endl;
        std::cout << "  [2] ./client 127.0.0.1:10069 info" << std::endl;
        std::cout << "  [3] ./client 127.0.0.1:10069 cmd ls -l (Linux)" << std::endl;
        std::cout << "  [4] ./client 127.0.0.1:10069 async_cmd /root/install.sh (Linux)" << std::endl;
        std::cout << "  [5] ./client 127.0.0.1:10069 cmd dir (Windows)" << std::endl;
        std::cout << "  [6] ./client 127.0.0.1:10069 update demo1.txt demo2.txt" << std::endl;
        std::cout << "  [7] ./client 127.0.0.1:10069 download demo2.txt demo3.txt" << std::endl;
        return 0;
    }

    std::string str_ip_port(argv[1]);
    std::string str_ip = str_ip_port.substr(0, str_ip_port.find_first_of(':'));
    std::string str_port = str_ip_port.substr(str_ip_port.find_first_of(':') + 1);

    if(!str_port.empty() && str_port != str_ip){
        port = atoi(str_port.c_str());
    }

    if(!isIPAddressValid(str_ip.c_str())){
        str_ip = "127.0.0.1";
    }

    /* 创建客户端 */
    std::cout << "RPC client tries to connect "<< str_ip << ":" << port << "." << std::endl;
    rpc::client c(str_ip.c_str(), port);

    /* port: argv[2] */
    if(!argv[2]){
        std::cout << "No thing to do." << std::endl;
        return 0;
    }
    else if(0 == strcmp("info", argv[2])){
        /* 获取系统信息 */
        get_server_info(&c);
    }
    else if(0 == strcmp("cmd", argv[2])){
        /* 调用远程命令 */
        int i = 3;
        if(!argv[i]){
            std::cout << "No thing to do." << std::endl;
            return 0;
        }

        /* 拼接命令 */
        std::string cmd(argv[i]);
        while(argv[++i]){
            cmd += std::string(" ") + argv[i];
        }

        if(cmd.empty()){
            std::cout << "No thing to do." << std::endl;
            return 0;
        }
        remote_cmd(&c, cmd.c_str());
    }
    else if(0 == strcmp("async_cmd", argv[2])){
        /* 调用远程命令 */
        int i = 3;
        if(!argv[i]){
            std::cout << "No thing to do." << std::endl;
            return 0;
        }

        /* 拼接命令 */
        std::string cmd(argv[i]);
        while(argv[++i]){
            cmd += std::string(" ") + argv[i];
        }

        if(cmd.empty()){
            std::cout << "No thing to do." << std::endl;
            return 0;
        }
        remote_async_cmd(&c, cmd.c_str());
    }
    else if(0 == strcmp("update", argv[2])){
        /* 上传文件 */
        if(!argv[3] || !argv[4]){
            std::cout << "No thing to do." << std::endl;
            return 0;
        }

        if(-1 == update_file(&c, argv[3], argv[4])){
            return -1;
        }
    }
    else if(0 == strcmp("download", argv[2])){
        /* 下载文件 */
        if(!argv[3] || !argv[4]){
            std::cout << "No thing to do." << std::endl;
            return 0;
        }

        if(-1 == download_file(&c, argv[3], argv[4])){
            return -1;
        }
    }
    else{
        std::cout << "Unsupported parameters." << std::endl;
        return 0;
    }

    return 0;
}

测试:Windows 上传文件到 Linux

  1. Linux 运行 server

    默认端口为 8080

    1
    
    ./server
    
  2. 双击 bat 脚本,脚本如下

    假设同一目录存在 test.tar 文件,上一级目录存在 client.exe 文件,需要拷贝到 linux 的 /home/jerry 目录,并解压执行;

    调用持续性脚本需要使用 async_cmd;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    setlocal
       
    set ip=192.168.2.2
    set port=8080
       
    ..\client.exe %ip%:%port% cmd rm /home/jerry/test* -rf
    ..\client.exe %ip%:%port% update test.tar /home/jerry/test.tar
    ..\client.exe %ip%:%port% cmd tar -vxf /home/jerry/test.tar -C /home/jerry
    ..\client.exe %ip%:%port% async_cmd /home/jerry/test/test.sh
       
    endlocal
    exit