Lua JSONRPC學習筆記

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   檔案   

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 encodetest = {  one=‘first‘,two=‘second‘,three={2,3,5}}jsonTest = json.encode(test)print(‘JSON encoded test is: ‘ .. jsonTest)-- Now JSON decode the json stringresult = 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 requestslocal 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 environmentfunction 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)endlocal rules = {{ match = ".", with = wsapi.xavante.makeHandler(wsapi_handler) }}local config = { server = {host = "*", port = 12345}, defaultHost = { rules = rules} }xavante.HTTP(config)xavante.start()

 

 

代碼實現了, 用戶端和服務通過JSONRPC調用,實現 echo 和 做平均計算的例子。

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.