linux下C语言jsonrpc服务实现


1.libev的编译安装

tar -zxvf libev-4.22.tar.gz
cd libev-4.22
./configure
make
make install
cd ..

2.jsonrpc-c的编译安装,已经包含cJSON库及一个简单服务例程

tar -zxvf jsonrpc-c-arma_stable.tar.gz
cd jsonrpc-c-arma_stable
./autoconf -i
./configure
make
make install
cd ..

3.测试服务

3.1运行服务

./jsonrpc-c-arma_stable/example/.libs/server

3.2测试

重新打开一个终端,执行如下两条命令,查看结果

echo "{\"method\":\"sayHello\"}" | nc localhost 1234

echo "{\"method\":\"exit\"}" | nc localhost 1234

4.例程代码server.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include "jsonrpc-c.h"

#define PORT 1234  // the port users will be connecting to

struct jrpc_server my_server;

cJSON * say_hello(jrpc_context * ctx, cJSON * params, cJSON *id) 
{
    return cJSON_CreateString("Hello!");
}

cJSON * exit_server(jrpc_context * ctx, cJSON * params, cJSON *id) 
{
    jrpc_server_stop(&my_server);
    return cJSON_CreateString("Bye!");
}

int main(void) 
{
    jrpc_server_init(&my_server, PORT);
    jrpc_register_procedure(&my_server, say_hello, "sayHello", NULL );
    jrpc_register_procedure(&my_server, exit_server, "exit", NULL );
    jrpc_server_run(&my_server);
    jrpc_server_destroy(&my_server);
    return 0;
}