-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent.lua
More file actions
106 lines (93 loc) · 2.12 KB
/
agent.lua
File metadata and controls
106 lines (93 loc) · 2.12 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
local skynet = require "skynet"
local netpack = require "netpack"
local socket = require "socket"
local helper = require "helper"
local WATCHDOG
local host
local send_request
local CMD = {}
local REQUEST = {}
local client_fd
function REQUEST:get()
print("get", self.key)
local r = skynet.call("SIMPLEDB", "lua", "get", self.key)
return { result = r }
end
function REQUEST:set()
print("set", self.key, self.value)
local r = skynet.call("SIMPLEDB", "lua", "set", self.key, self.value)
end
function REQUEST:handshake()
return { msg = "Welcome to skynet, I will send heartbeat every 5 sec." }
end
function REQUEST:quit()
skynet.call(WATCHDOG, "lua", "close", client_fd)
end
local function request(str)
print("agent recive str = "..str)
local cmd = helper.unserialize(str)
for k,v in pairs(cmd) do
print(k,v)
end
local f = assert(REQUEST[cmd.cmd])
local r = f(cmd)
return r
end
local function send_package(pack)
if type(pack) == "table" then
pack = helper.serialize(pack)
end
local package = string.pack(">s2", pack)
socket.write(client_fd, package)
end
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
unpack = skynet.tostring,
dispatch = function (_, _, str)
-- if type == "REQUEST" then
-- local ok, result = pcall(request, str)
-- 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
local ok, result = pcall(request, str)
if ok then
if result then
send_package(result)
end
else
skynet.error(result)
end
end
}
function CMD.start(conf)
local fd = conf.client
local gate = conf.gate
WATCHDOG = conf.watchdog
skynet.fork(function()
while true do
send_package("heartbeat")
skynet.sleep(500)
end
end)
client_fd = fd
skynet.call(gate, "lua", "forward", fd)
end
function CMD.disconnect()
-- todo: do something before exit
skynet.exit()
end
skynet.start(function()
skynet.dispatch("lua", function(_,_, command, ...)
local f = CMD[command]
skynet.ret(skynet.pack(f(...)))
end)
end)