mirror of
https://github.com/cloudwu/skynet.git
synced 2026-07-24 03:53:09 +00:00
use sproto instead of cjson
This commit is contained in:
@@ -1,40 +1,75 @@
|
||||
local skynet = require "skynet"
|
||||
local jsonpack = require "jsonpack"
|
||||
local netpack = require "netpack"
|
||||
local socket = require "socket"
|
||||
local sproto = require "sproto"
|
||||
local bit32 = require "bit32"
|
||||
|
||||
local rpc
|
||||
|
||||
local CMD = {}
|
||||
|
||||
local REQUEST = {}
|
||||
local client_fd
|
||||
|
||||
local function send_client(v)
|
||||
socket.write(client_fd, netpack.pack(jsonpack.pack(0, {true, v})))
|
||||
function REQUEST:get()
|
||||
print("get", self.what)
|
||||
local r = skynet.call("SIMPLEDB", "lua", "get", self.what)
|
||||
return { result = r }
|
||||
end
|
||||
|
||||
local function response_client(session,v)
|
||||
socket.write(client_fd, netpack.pack(jsonpack.response(session,v)))
|
||||
function REQUEST:set()
|
||||
print("set", self.what, self.value)
|
||||
local r = skynet.call("SIMPLEDB", "lua", "set", self.what, self.value)
|
||||
return { ok = true }
|
||||
end
|
||||
|
||||
function REQUEST:handshake()
|
||||
return { msg = "Welcome to skynet" }
|
||||
end
|
||||
|
||||
local function request(name, args, response)
|
||||
local f = assert(REQUEST[name])
|
||||
local r = f(args)
|
||||
if response then
|
||||
return response(r)
|
||||
end
|
||||
end
|
||||
|
||||
local function send_package(pack)
|
||||
local size = #pack
|
||||
local package = string.char(bit32.extract(size,8,8)) ..
|
||||
string.char(bit32.extract(size,0,8))..
|
||||
pack
|
||||
|
||||
socket.write(client_fd, package)
|
||||
end
|
||||
|
||||
skynet.register_protocol {
|
||||
name = "client",
|
||||
id = skynet.PTYPE_CLIENT,
|
||||
unpack = function (msg, sz)
|
||||
return jsonpack.unpack(skynet.tostring(msg,sz))
|
||||
return rpc:dispatch(msg, sz)
|
||||
end,
|
||||
dispatch = function (_, _, session, args)
|
||||
local ok, result = pcall(skynet.call,"SIMPLEDB", "lua", table.unpack(args))
|
||||
if ok then
|
||||
response_client(session, { true, result })
|
||||
dispatch = function (_, _, type, ...)
|
||||
if type == "REQUEST" then
|
||||
local ok, result = pcall(request, ...)
|
||||
if ok then
|
||||
if result then
|
||||
send_package(result)
|
||||
end
|
||||
else
|
||||
skynet.error(result)
|
||||
end
|
||||
else
|
||||
response_client(session, { false, "Invalid command" })
|
||||
assert(type == "RESPONSE")
|
||||
error "This example doesn't support request client"
|
||||
end
|
||||
end
|
||||
}
|
||||
|
||||
function CMD.start(gate , fd)
|
||||
function CMD.start(gate, fd, proto)
|
||||
rpc = sproto.new(proto):rpc "package"
|
||||
client_fd = fd
|
||||
skynet.call(gate, "lua", "forward", fd)
|
||||
send_client "Welcome to skynet"
|
||||
end
|
||||
|
||||
skynet.start(function()
|
||||
|
||||
Reference in New Issue
Block a user