|
1 | 1 | # mjsonrpc - 基于 C 语言的 JSON-RPC 2.0 的服务端消息解析器和生成器 |
2 | 2 |
|
| 3 | +      |
| 4 | + |
3 | 5 | ### 介绍 |
4 | 6 |
|
5 | 7 | 本项目轻量,依赖少,可以集成进各种通信方式(TCP、UDP、消息队列等),使用简单(只有少量功能函数),性能好(哈希值计算索引,无需轮询所有方法),并支持批量调用 (JSON Array) 、自动根据请求生成对应错误信息或构造自定义的错误信息,以及通知请求等功能。 |
6 | 8 |
|
7 | 9 | ### 如何使用 |
8 | 10 |
|
9 | | -将项目源文件(`mjsonrpc.c`、`mjsonrpc.h`)和 `cJSON` 库加入自己的工程一同编译即可,也可以自行编译为动态库进行链接。 |
| 11 | +将项目源文件(`mjsonrpc.c`、`mjsonrpc.h`)和 `cJSON` 库加入自己的工程一同编译即可,也可以自行编译为动态库进行链接或在本仓库 [releases](https://github.com/sfxfs/mjsonrpc/releases) 中下载已经编译好的二进制版本。 |
10 | 12 |
|
11 | 13 | ### 函数定义 |
12 | 14 |
|
13 | | -详细 API 描述请见 `src/mjsonrpc.h`。 |
| 15 | +详细 API 描述请见 `src/mjsonrpc.h`,或 [本仓库 Doxygen 文档](https://sfxfs.github.io/mjsonrpc)。 |
14 | 16 |
|
15 | 17 | ### 示例 |
16 | 18 |
|
|
19 | 21 | #include <stdio.h> |
20 | 22 | #include <stdlib.h> |
21 | 23 |
|
22 | | -// Define a simple JSON-RPC method |
| 24 | +// 定义一个简单的 JSON-RPC 方法 |
23 | 25 | cJSON *hello_world(mjrpc_func_ctx_t *context, cJSON *params, cJSON *id) { |
24 | 26 | cJSON *result = cJSON_CreateString("Hello, World!"); |
25 | 27 | return result; |
26 | 28 | } |
27 | 29 |
|
28 | 30 | int main() { |
29 | | - // Initialize mjrpc_handle_t |
| 31 | + // 初始化 mjrpc_handle_t |
30 | 32 | mjrpc_handle_t* handle = mjrpc_create_handle(0); |
31 | 33 |
|
32 | | - // Add a method |
| 34 | + // 添加一个方法 |
33 | 35 | mjrpc_add_method(handle, hello_world, "hello", NULL); |
34 | 36 |
|
35 | | - // Construct a JSON-RPC request |
| 37 | + // 生成 JSON-RPC 请求 |
36 | 38 | const char *json_request = "{\"jsonrpc\":\"2.0\",\"method\":\"hello\",\"id\":1}"; |
37 | 39 |
|
38 | | - // Process the request |
| 40 | + // 处理请求 |
39 | 41 | int result; |
40 | 42 | char *json_response = mjrpc_process_str(handle, json_request, &result); |
41 | 43 |
|
42 | | - // Check return code |
| 44 | + // 检查返回值 |
43 | 45 | if (result != MJRPC_RET_OK) { |
44 | 46 | printf("Error processing request: %d\n", result); |
45 | 47 | } |
46 | 48 |
|
47 | | - // Check response string |
| 49 | + // 检查响应字符串 |
48 | 50 | if (json_response) { |
49 | 51 | printf("Response: %s\n", json_response); |
50 | 52 | free(json_response); |
51 | 53 | } |
52 | 54 |
|
53 | | - // Cleanup |
| 55 | + // 释放句柄 |
54 | 56 | mjrpc_destroy_handle(handle); |
55 | 57 |
|
56 | 58 | return 0; |
|
0 commit comments