Lua JSONRPC Learning Notes

Source: Internet
Author: User
Tags unpack

JSON RPC

JSON RPC uses the JSON data format to perform remote invocation methods.

function with XMLRPC, but compared to XMLRPC, the jsonrpc is lighter, and JSON is more data-efficient and more readable.

Official website:

http://www.json-rpc.org/

JSONRPC protocol Specification:

Http://www.json-rpc.org/wiki/specification

JSONRPC projects implemented by LUA:

Https://github.com/craigmj/json4lua

http://json.luaforge.net/

JSON

JSON is a string-like format for data organization, so that it can be transmitted in a way that is syntactically identical to JavaScript objects (JS object Notation).

Website:

http://www.json.org/

The JSON project implemented by LUA:

Https://github.com/craigmj/json4lua

LUA JSON encoding and decoding

Download the JSON LUA implementation code package, and after extracting it, place the JSON folder under Lua path, which is the LUA installation directory.

Download URL:

Https://github.com/craigmj/json4lua

Where the example folder has demo code Example.lua, demonstrates how to encode a LUA table as a JSON string, and how to revert this string to 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

The LUA JSON download installation package, which already includes the JSON RPC implementation, only needs to test JSONRPC's client and server-side examples from example.

The client relies on Luasocket to initiate an HTTP request.

The server-side code has been modified to trigger execution when the host and Xavante are connected.

Client:

require("Json.rpc") result,Error= Json.rpc.call ("http://localhost:12345","Echo","Test echo!")Print("Echo call=".. Result)Print("\ n") result,Error= Json.rpc.call ("http://localhost:12345","Average",1,3)Print("average=".. Result.average)

Server-side code:

Xavante =require("Xavante") Wsapi=require("Wsapi") Wsapi.xavante=require("Wsapi.xavante") Wsapi.request=require("wsapi.request")require('JSON')--The Lua class that's to serve JSON RPC requestsLocalMyServer ={echo=function(msg)returnMsgEnd, average=function(...) LocalTotal=0    LocalCount=0     forI=1, TABLE.GETN (ARG) Do Total= Total +Arg[i] Count= Count +1    End    return{average= Total/count, sum = Total, n=Count}End}
--JSON RPC server-side processing principal programLocal functionserve (Luaclass, Packreturn, req)LocalPostData = req. Post.post_data--SAPI. Request.getpostdata ()--[[{"id": 1, "method": "echo", "params": ["Hi There"]}]-- --@TODO Catch An error condition on decoding the data LocalJsonrequest =Json.decode (postdata)LocalJsonresponse ={} jsonresponse.id=jsonrequest.idLocalMETHOD =luaclass[Jsonrequest.method]if notMethod ThenJsonresponse.Error='Method'.. Jsonrequest.method.'does not exist on this server.' Else LocalCallresult = {Pcall(Method,Unpack(Jsonrequest.params))}ifcallresult[1] Then --Function Call successfull Table.remove(Callresult,1) ifPackreturn andTABLE.GETN (Callresult) >1 ThenJsonresponse.result=CallresultElseJsonresponse.result=Unpack(Callresult)--Nb:does not support multiple argument returns End ElseJsonresponse.Error= callresult[2] End End --Output The result --Todo:how to being sure that the result and error tags is there even when they is nil in Lua? --Can force them by hand ...? returnJson.encode (jsonresponse)End---WSAPI Handler--@param wsapi_env WSAPI EnvironmentfunctionWsapi_handler (wsapi_env)Localheaders = {["Content-type"] ="Text/plain" } Localreq =wsapi.request.new (wsapi_env)LocalR = Serve (MyServer,Nil, req)Print("r=".. R) headers["Content-length"] =ToString(#R)Local functionxmlrpc_reply (wsapienv)Coroutine.yield(R)End return $, headers,Coroutine.wrap(xmlrpc_reply)EndLocalRules = {{match =".", with =Wsapi.xavante.makeHandler (Wsapi_handler)}}LocalConfig = {Server = {host ="*", Port =12345}, Defaulthost = {rules =Rules}} Xavante. HTTP (config) xavante.start ()

The code is implemented, and the client and the service are called through JSONRPC to achieve echo and do the averaging calculation example.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.