Lua JSONRPC学习笔记
JSON RPC
JSON RPC 为利用json数据格式来执行远程调用方式,
作用同xmlrpc,不过与xmlrpc相比, jsonrpc更加轻量,json更加节省数据量,更加可读性高。
官网网站:
http://www.json-rpc.org/
JSONRPC协议规范:
http://www.json-rpc.org/wiki/specification
lua实现的jsonrpc项目:
https://github.com/craigmj/json4lua
http://json.luaforge.net/
JSON
JSON为一种字符串方式数据组织的格式,以便于传输, 其语法同JAVASCRIPT对象写法(JS Object Notation)。
官网:
http://www.json.org/
lua实现的json项目:
https://github.com/craigmj/json4lua
LUA JSON 编解码
下载 json lua实现代码包, 解压后,将json文件夹放到lua path下,即lua安装目录下。
下载网址:
https://github.com/craigmj/json4lua
其中example文件夹下有演示代码 example.lua, 演示了如何将 一个 lua table编码为JSON字符串, 又如何将此字符串,恢复为LUA table。
--[[
JSON4Lua example script.
Demonstrates the simple functionality of the json module.
]]--
json = require('json') -- Object to JSON encode
test = {
one='first',two='second',three={,,}
} jsonTest = json.encode(test) print('JSON encoded test is: ' .. jsonTest) -- Now JSON decode the json string
result = json.decode(jsonTest) print ("The decoded table result:")
table.foreach(result,print)
print ("The decoded table result.three")
table.foreach(result.three, print)
LUA JSON RPC
lua json的下载安装包,已经包括 json rpc的实现, 只需要从example中测试 jsonrpc的 客户端和 服务器端例子即可。
客户端依赖 luasocket 来发起http请求。
服务器端代码经过改造, 宿主与xavante, 有连接到来时, 触发执行。
客户端:
require ("json.rpc")
result, error = json.rpc.call("http://localhost:12345","echo","Test echo!")
print("echo call="..result)
print("\n\n")
result, error = json.rpc.call("http://localhost:12345","average", , )
print("average="..result.average)
服务器端代码:
xavante = require("xavante")
wsapi = require("wsapi")
wsapi.xavante = require("wsapi.xavante")
wsapi.request = require("wsapi.request")
require ('json')
-- The Lua class that is to serve JSON RPC requests
local myServer = {
echo = function (msg) return msg end,
average = function(...)
local total=
local count=
for i=, table.getn(arg) do
total = total + arg[i]
count = count +
end
return { average= total/count, sum = total, n=count }
end
}
-- JSON RPC 服务器端处理主体程序
local function serve(luaClass, packReturn, req)
local postData = req.POST.post_data -- SAPI.Request.getpostdata() --[[{ "id":1, "method":"echo","params":["Hi there"]}]] --
-- @TODO Catch an error condition on decoding the data
local jsonRequest = json.decode(postData)
local jsonResponse = {}
jsonResponse.id = jsonRequest.id
local method = luaClass[ jsonRequest.method ]
if not method then
jsonResponse.error = 'Method ' .. jsonRequest.method .. ' does not exist at this server.'
else
local callResult = { pcall( method, unpack( jsonRequest.params ) ) }
if callResult[] then -- Function call successfull
table.remove(callResult,)
if packReturn and table.getn(callResult)> then
jsonResponse.result = callResult
else
jsonResponse.result = unpack(callResult) -- NB: Does not support multiple argument returns
end
else
jsonResponse.error = callResult[]
end
end
-- Output the result
-- TODO: How to be sure that the result and error tags are there even when they are nil in Lua?
-- Can force them by hand... ?
return json.encode( jsonResponse )
end
--- WSAPI handler
-- @param wsapi_env WSAPI environment
function wsapi_handler(wsapi_env)
local headers = { ["Content-type"] = "text/plain" }
local req = wsapi.request.new(wsapi_env)
local r = serve(myServer, nil, req)
print("r="..r)
headers["Content-length"] = tostring(#r)
local function xmlrpc_reply(wsapienv)
coroutine.yield(r)
end
return , headers, coroutine.wrap(xmlrpc_reply)
end
local rules = {{ match = ".", with = wsapi.xavante.makeHandler(wsapi_handler) }}
local config = { server = {host = "*", port = }, defaultHost = { rules = rules} }
xavante.HTTP(config)
xavante.start()
代码实现了, 客户端和服务通过JSONRPC调用,实现 echo 和 做平均计算的例子。

Lua JSONRPC学习笔记的更多相关文章
- lua本学习笔记功能
Lua本学习笔记功能 1. 函数返回 指定任务的主要功能是完成,在这种情况下,函数被用作调用语句.函数可以计算并返回值,在这种情况下,作为分配值表达式语句使用. 语法: funcationfunc_ ...
- GJM : Lua 语言学习笔记
Lua笔记 容易与C/C++整合 Lua所提供的机制是C所不善于的:高级语言,动态结构,简洁,易于测试和调试. Lua特有的特征: `1:可扩展性.卓越的扩展性导致了很多人将Lua用作搭建领域语言的工 ...
- LUA table学习笔记
function printT( ... ) for i,v in ipairs(...) do print(i,v) end end t1={} t2={} t3={} table.insert(t ...
- Lua 基础 -- 学习笔记
标签(空格分隔): Lua 1. Lua可以一次性给多个变量赋值 变量比赋值多,多的变量就赋值nil 变量比赋值少,多的赋值舍弃 local a, b, c = 1, 2, 3 print( a, b ...
- lua学习笔记
工作需要,上周对lua赶进度似地学习了一遍,主要参考<lua中文教程>一书,中间参考一些<lua游戏开发实践>,首先说说这两本书,后者不适合初学,里面是对一个游戏脚本系统进行粗 ...
- [转]LUA 学习笔记
Lua 学习笔记 入门级 一.环境配置 方式一: 1.资源下载http://www.lua.org/download.html 2.用src中的源码创建了一个工程,注释调luac.c中main函数,生 ...
- uLua学习笔记(三):Unity3D和Lua之间的相互调用
这篇笔记主要集中学习一下uLua和Unity3D之间相互调用的方法,我们导入了uLua之后,现在会弹出一个类似学习屏幕的东西,如下: 先赞一个! Unity3D调用Lua Unity3D调用Lua的方 ...
- Lua 学习笔记(一)
Lua学习笔记 1.lua的优势 a.可扩张性 b.简单 c.高效率 d.和平台无关 2.注释 a.单行注释 -- b.多行注释 --[[ --]] 3.类型和 ...
- Lua学习笔记6:C++和Lua的相互调用
曾经一直用C++写代码.话说近期刚换工作.项目组中的是cocos2dx-lua,各种被虐的非常慘啊有木有. 新建cocos2dx-lua项目.打开class能够发现,事实上就是C++项 ...
随机推荐
- 在ScrollView下加入的组件,不能自动扩展到屏幕高度
ScrollView中的组件设置android:layout_height="fill_parent"不起作用的解决办法 在ScrollView中添加一个android:fillV ...
- 【BZOJ】1535: [POI2005]Sza-Template
题意 给一个串\(s(1 \le |s| \le 500000)\),求一个最长的串,使得这个串能覆盖整个串(可以重叠). 分析 首先这个串肯定是前缀也肯定是后缀. 题解 对串kmp后,建立\(fai ...
- Codeforces Beta Round #1
A题,水题. B题也是水题,弄的比较麻烦,前几天队内赛见过,水题怎么水都能过. C题 题意:给出正n边形上的三个点,求最小的正n边形的面积. 以前貌似见过此题.思路也没什么进展,就是枚举n,通过旋转a ...
- Crystal Reports 2008(水晶报表) 安装
这篇blog主要是介绍Crystal Reports2008(水晶报表)的安装. 首先我们应该知道Crystal Reports 有什么作用? 从这里Crystal Reports 你可以了解到它的一 ...
- JS相关环境搭建:Nodejs、karma测试框架、jsDuck、Express
第一章:压缩js(nodejs,uglify) 第一步:安装nodejs环境 直接下载http://www.nodejs.org/download/ 下载完成后直接下一步下一步即可,完了我们就具有no ...
- Centos 安装 NodeJS
准备命令: yum -y install gcc make gcc-c++ openssl-devel wget 下载源码及解压: wget http://nodejs.org/dist/v0.10. ...
- nginx“虚拟目录”不支持php的解决办法
这几天在配置Nginx,PHP用FastCGI,想装一个phpMyAdmin管理数据库,phpMyAdmin不想放在网站根目录 下,这样不容易和网站应用混在一起,这样phpMyAdmin的目录就放在别 ...
- Android事件处理
含义:为用户动作提供响应就是事件处理. Android提供了强大的事件处理机制:基于监听的事件处理.基于回调的事件处理. 一.基于监听的事件处理 监听的处理模型主要涉及三类对象 >Event S ...
- 内置函数----整理、例题 、xmin
-----------数值函数 ---绝对值 select abs(-123) from dual; --求模 select mod (12,5) from dual; --取整 --上限值 sele ...
- hdu Virtual Friends
这题是一个很简单额并查集的题目,首先第一步是要用map将字符串映射为整型,这样方便后面的处理,然后就是用一个rank[]数组来记录每个朋友圈的人数.之后就是简单的并查集操作了. 这里给出一组测试案例: ...