• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

LuaJSONRPC学习笔记

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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={2,3,5}
}

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", 1, 3)
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=0
    local count=0
    for i=1, table.getn(arg) do
      total = total + arg[i]
      count = count + 1
    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[1] then -- Function call successfull table.remove(callResult,1) if packReturn and table.getn(callResult)>1 then jsonResponse.result = callResult else jsonResponse.result = unpack(callResult) -- NB: Does not support multiple argument returns end else jsonResponse.error = callResult[2] 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 200, headers, coroutine.wrap(xmlrpc_reply) end local rules = {{ match = ".", with = wsapi.xavante.makeHandler(wsapi_handler) }} local config = { server = {host = "*", port = 12345}, defaultHost = { rules = rules} } xavante.HTTP(config) xavante.start()

 

 

代码实现了, 客户端和服务通过JSONRPC调用,实现 echo 和 做平均计算的例子。

 

 

 

 

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ctagsluaprotobuf发布时间:2022-07-22
下一篇:
Cocos2d-x3.1.1Lua演示样例ActionsProgressTest(进度条)发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap