2014年01月27日 星期一 17:20
通过最近几天的研究,我发现cppcms的API有更高级更丰富的功能,比如URL的映射,JSON value与常用数据类型的转换。其配置文件也有很丰富的选项,比如多线程和多进程模式,网络参数等。
代码示例如下:
#include <cppcms/application.h> #include <cppcms/applications_pool.h> #include <cppcms/service.h> #include <cppcms/http_response.h> #include <cppcms/rpc_json.h> #include <cppcms/json.h> #include <cppcms/mount_point.h> #include <map> #include <string> #include <exception> #include <iostream> using namespace std; using cppcms::rpc::json_rpc_server; using cppcms::rpc::json_method; class calc_service : public json_rpc_server { public: calc_service(cppcms::service &srv) : json_rpc_server(srv) { bind("sum", json_method(&calc_service::sum,this),method_role); bind("div", json_method(&calc_service::div,this),method_role); } void sum(int x,int y) { cppcms::json::value v; v["x"]=x; v["y"]=y; v["result"]=x+y; return_result(v); } void div(int x,int y) { if(y == 0) { return_error("Division by zero."); } else { return_result(x/y); } } }; class hello_service : public json_rpc_server { public: hello_service(cppcms::service &srv) : json_rpc_server(srv) { bind("hello", json_method(&hello_service::hello,this),method_role); bind("hello_all", json_method(&hello_service::hello_all,this),method_role); bind("hello_x", json_method(&hello_service::hello_x,this),method_role); } void hello(string name) { string say="Hello, " + name + "."; return_result(say); } void hello_all(vector<string> names) { string say="Hello, "; for(unsigned i=0;i<names.size();i++) { say += names[i] + " "; } return_result(say); } void hello_x(cppcms::json::value val) { return_result(val); } }; int main(int argc,char **argv) { try { cppcms::service srv(argc,argv); srv.applications_pool().mount( cppcms::applications_factory<calc_service>(), cppcms::mount_point("/calc") ); srv.applications_pool().mount( cppcms::applications_factory<hello_service>(), cppcms::mount_point("/hello") ); srv.run(); } catch (exception const &e) { cerr << e.what() << endl; } return 0; }
配置文件示例:
{ "service" : { "api" : "http", "ip" : "0.0.0.0", "port" : 8080, "worker_threads" : 50, "worker_processes" : 4, "backlog" : 1024, "application_pool_size" : 128, }, "http" : { "script_names" : [ "/calc","/hello" ] } }
Zeuux © 2024
京ICP备05028076号