require "jsonrpc/tcpsock" JSONRPC = JSONRPC or {} -- dumb hack: lua apparently can't manipulate arg tuples very effectively -- and messing around with arg tables is even dumber than this -- can we do this any better in 5.1? local function result_call(cb, c, method, xid, ...) return cb(c, unpack(arg)) end function JSONRPC.make_server(port, request_methods, notify_methods, conn_callback, disconn_callback) return TCP.make_server(port, function(newconn, err) -- new connection -- connection from.. some host but i can't request the peer -- address because that isn't in the API.. blah if newconn then -- register a notify method function newconn:notify(...) --print('conn:notify: '..StrTable(arg)) newconn:Send(json.encode{'notify', unpack(arg)}..'\n') end conn_callback(newconn) end end, function(c, line) -- receive line local ok,req = pcall(json.decode, line) if not ok or type(req) ~= "table" then print('Invalid JSON from '..tostring(c)..': '..req) elseif req[1] == 'notify' then local method = req[2] if notify_methods[method] then xpcall(function() -- strip off 'notify' and method (instead of method and xid).. same result result_call(notify_methods[method], c, unpack(req)) end, function(err) log.error("rpcserv notify"..StrTable(req)..":"..tostring(err)) end) end else --print('JSONRPC from '..c.tcp:GetPeerName()..': '..StrTable(req)) local method, reqid = unpack(req) if request_methods[method] then local result xpcall(function() c:Send(json.encode{'result', reqid, result_call(request_methods[method], c, unpack(req))}..'\n') end, function(err) c:Send(json.encode{'error', reqid, err}..'\n') end) else c:Send(json.encode{'error', reqid, 'no such method'}..'\n') end end end, function(c) -- disconnect disconn_callback(c) end) end