用CppCMS实现web site并同时支持json_rpc服务

刘怀宇

1.将cppcms-0.99.10/examples/json_rpc/rpc.cpp文件中的json_service类拷贝到
examples/templates/hello-tmpl.cpp 中
2.修改hello-tmpl.cpp 中的main函数,添加两个服务

int main(int argc,char ** argv)
{
    try {
        cppcms::service srv(argc,argv);
        srv.applications_pool().mount(cppcms::applications_factory<my_hello_world>() , cppcms::mount_point(std::string("/html")) );
	srv.applications_pool().mount(cppcms::applications_factory<json_service>() , cppcms::mount_point(std::string("/jsonrpc")) );
        srv.run();
    }
    catch(std::exception const &e) {
        std::cerr<<e.what()<<std::endl;
    }
}


3.修改config.js 文件,添加 script_names : /jsonrpc , /html
{
    "service" : {
	"api" : "http",
	"port" : 8080
    },
    "http" : {
	"script_names" : ["/jsonrpc","/html"]
    }
}




4.在first.tmpl 中使用如下的html文本 替换掉原来的html

<html>
	<body>
	<script type="text/javascript">
	function call() {
	        
	        var xhr = new XMLHttpRequest();
	        xhr.open("post", 'http://localhost:8080/jsonrpc');
	        // Required by JSON-RPC over HTTP
	        xhr.setRequestHeader("Content-Type","application/json");
	
	        // It is better to use real formatter like JSON.js
	        x=parseInt(document.getElementById('x').value);
	        y=parseInt(document.getElementById('y').value);
	        var request = '{"method":"div","params":[' + x + ',' + y +'],"id":1}';
	
	        xhr.onreadystatechange = function() {
	                if (xhr.readyState === 4) {
	                        res = 'Unknown Error';
	                        if(xhr.status === 200) {
	                                // Don't call eval in real code use some parser
	                                var result = eval('(' + xhr.responseText + ')');
	                                if(result.error==null) {
	                                        res = result.result;
	                                }
	                                else {
	                                        res = result.error;
	                                }
	                        }
	                        document.getElementById('result').innerHTML = res;
	                }
	        }
	        xhr.send(request); 
	        return false;
	}
	</script>
	<form onsubmit="return call();">
	<p>
	<input type="text" id="x" />
	<input type="submit" value="/" />
	<input type="text" id="y" /> = 
	<span id="result"></span>
	</p>
	</form>
	</body>
</html>



5.make
6. 执行生成的hello-tmpl     ./hello-tmpl -c config.js

7. 访问http://localhost:8080/html 在返回的html页面中计算除法,即可成功访问后台的json服务,得到结果

8.注意,IE6不支持JSON_RPC技术。



原文链接: http://blog.csdn.net/sheismylife/article/details/6760690

你可能感兴趣的:(用CppCMS实现web site并同时支持json_rpc服务)