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
|
local json = require 'json'
local TIMEOUT = 1.0
local ID = 0
local BUF = {}
local function notify(self, method, params)
local pack = {
jsonrpc = '2.0',
method = method,
params = params,
}
local content = json.encode(pack)
local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
io.write(buf)
end
local function request(self, method, params, callback)
ID = ID + 1
local pack = {
jsonrpc = '2.0',
id = ID,
method = method,
params = params,
}
local content = json.encode(pack)
local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
BUF[ID] = {
callback = callback,
timeout = os.clock() + TIMEOUT,
}
io.write(buf)
end
local function requestWait(self, method, params, callback)
ID = ID + 1
local pack = {
jsonrpc = '2.0',
id = ID,
method = method,
params = params,
}
local content = json.encode(pack)
local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
BUF[ID] = {
callback = callback,
}
io.write(buf)
end
local function response(self, id, data)
data.jsonrpc = '2.0'
data.id = id
local content = json.encode(data)
local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
io.write(buf)
end
local function recieve(self, proto)
local id = proto.id
local data = BUF[id]
if not data then
log.warn('Recieve id not found: ', table.dump(proto))
return
end
BUF[id] = nil
if data.timeout and os.clock() > data.timeout then
log.warn('Recieve timeout: ', table.dump(proto))
local info = debug.getinfo(data.callback, 'S')
log.warn('Call back info: ', info.source, info.linedefined)
return
end
if proto.error then
log.warn('Recieve: ', table.dump(proto.error))
return
end
if data.callback then
data.callback(proto.result)
end
end
return {
notify = notify,
request = request,
requestWait = requestWait,
response = response,
recieve = recieve,
}
|