目錄
-
- 0 概述
-
- 0.0 參考
- 0.1 HTTP 服務
- 0.2 JSON RPC HTTP錯誤碼
- 0.3 目錄結構
- 1 使用
-
- 1.1 接口通路示例
- 1.2 方法注冊
- 1.3 修改監聽端口
- 4 源碼擷取
0 概述
0.0 參考
GitHub - hmng/jsonrpc-c: JSON-RPC in C (server only for now)
GitHub - cesanta/mongoose: Embedded Web Server
GitHub - DaveGamble/cJSON: Ultralightweight JSON parser in ANSI C
0.1 HTTP 服務
HTTP-JRPC-C 内置了HTTP服務用于提供JRPC API服務和靜态檔案服務。純C語言編寫。在最開始我是使用的hmng/jsonrpc-c 但是由于該服務隻能提供TCP連接配接,不太适用于我的應用場景,是以結合mongoos庫對其進行了重構。
0.2 JSON RPC HTTP錯誤碼
錯誤碼 sys-error | 描述 |
---|---|
000 | 正常 |
101 | 未找到指定的方法 |
102 | 格式錯誤 |
103 | 請求方法錯誤 |
0.3 目錄結構
一級 | 二級 | 三級 | 四級 | 檔案說明 |
---|---|---|---|---|
build | 編譯輸出目錄 | |||
bin | 編譯輸出目錄,也是運作目錄 | |||
lib | ||||
web | JRPC-HTTP會預設窮舉該目錄下的檔案作為伺服器靜态檔案 | |||
index.html | 靜态伺服器預設界面,可在運作JRPC-HTTP後嘗試通路http://xxx.xxx.xxx.xxx:8000 | |||
JRPC-HTTP | 編譯後得到的可執行檔案,在Ubuntu 16下使用GCC編譯。 | |||
CommLib | ||||
inc | ||||
cJSON.h | cJSON.h頭檔案 | |||
comm.h | 常用函數,如delay_ms延時函數 | |||
src | ||||
cJSON.c | cJSON.h源檔案 | |||
comm.c | 常用函數,如delay_ms延時函數 | |||
JRPC | ||||
inc | ||||
jsonrpc-c.h | jsonrpc頭檔案 | |||
mongoose.h | mongoose頭檔案 | |||
src | ||||
jsonrpc-c.c | jsonrpc源檔案 | |||
mongoose.c | mongoose源檔案 |
1 使用
1.1 接口通路示例
方法原型 main.c:30
cJSON * add(jrpc_context * ctx, cJSON * params, cJSON *id) {
cJSON * a = cJSON_GetArrayItem(params,0);
cJSON * b = cJSON_GetArrayItem(params,1);
return cJSON_CreateNumber(a->valueint + b->valueint);
}
POST方法,路徑:http://xxx.xxx.xxx.xxx:8000
使用POSTMAN測試如下:
1.2 方法注冊
在main()中建立了一個HTTP線程,線程的一開始會對JRPC進行初始化。在初始化完成後可以在任何時候調用jrpc_register_procedure()注冊方法。
//線程句柄
pthread_t HTTP_main_thread_tid;
//RPC 方法
cJSON * say_hello(jrpc_context * ctx, cJSON * params, cJSON *id) {
return cJSON_CreateString("Hello!");
}
cJSON * add(jrpc_context * ctx, cJSON * params, cJSON *id) {
cJSON * a = cJSON_GetArrayItem(params,0);
cJSON * b = cJSON_GetArrayItem(params,1);
return cJSON_CreateNumber(a->valueint + b->valueint);
}
extern struct jrpc_server my_server;
void main(int argc, char *argv[])
{
int ret;
//擷取運作路徑
ProgramRootPath = malloc(strlen(argv[0]));
memset(ProgramRootPath,0x00,strlen(argv[0]));
memcpy(ProgramRootPath,argv[0],strlen(argv[0])-17);
printf("PATH : %s",ProgramRootPath);
//建立HTTP線程
ret = pthread_create(&HTTP_main_thread_tid,NULL,HTTP_MainThread,NULL);
jrpc_register_procedure(&my_server, say_hello, "sayHello", NULL );
jrpc_register_procedure(&my_server, add, "add", NULL );
while (1)
{
delay_ms(2000);
}
}
1.3 修改監聽端口
程式預設監聽的端口号為8000,可在/JRPC/src/jsonrpc-c.c中修改為你所需要的端口。
void *HTTP_MainThread(void *arg)
{
struct mg_mgr mgr;
mg_mgr_init(&mgr);
printf("Server listen on port 8000\r\n");
//監聽位址與端口設定
mg_http_listen(&mgr, "0.0.0.0:8000", fn, NULL); // Create listening connection
while (1)
{
mg_mgr_poll(&mgr, 100); // Block forever
}
}
4 源碼擷取
gitee擷取源碼