forked from cloudwu/skynet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.lua
80 lines (69 loc) · 1.64 KB
/
agent.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
local skynet = require "skynet"
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
function REQUEST:get()
print("get", self.what)
local r = skynet.call("SIMPLEDB", "lua", "get", self.what)
return { result = r }
end
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 rpc:dispatch(msg, sz)
end,
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
assert(type == "RESPONSE")
error "This example doesn't support request client"
end
end
}
function CMD.start(gate, fd, proto)
rpc = sproto.new(proto):rpc "package"
client_fd = fd
skynet.call(gate, "lua", "forward", fd)
end
skynet.start(function()
skynet.dispatch("lua", function(_,_, command, ...)
local f = CMD[command]
skynet.ret(skynet.pack(f(...)))
end)
end)