diff options
author | 最萌小汐 <sumneko@hotmail.com> | 2018-12-18 14:30:52 +0800 |
---|---|---|
committer | 最萌小汐 <sumneko@hotmail.com> | 2018-12-18 14:30:52 +0800 |
commit | a064ab3a5c024b02235e041a2d0941fd094843cd (patch) | |
tree | 7d7b048c7ce7452c0423083acd513040988a6fac /server/src/rpc.lua | |
parent | 8e7cea5ebe6e41b817bda532ad077013f12bb4e5 (diff) | |
download | lua-language-server-a064ab3a5c024b02235e041a2d0941fd094843cd.zip |
简单的rpc
Diffstat (limited to 'server/src/rpc.lua')
-rw-r--r-- | server/src/rpc.lua | 60 |
1 files changed, 60 insertions, 0 deletions
diff --git a/server/src/rpc.lua b/server/src/rpc.lua new file mode 100644 index 00000000..559853e0 --- /dev/null +++ b/server/src/rpc.lua @@ -0,0 +1,60 @@ +local json = require 'json' + +local TIMEOUT = 1.0 + +local ID = 0 +local BUF = {} + +local function notify(self, data) + data.jsonrpc = '2.0' + local content = json.encode(data) + local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content) + io.write(buf) +end + +local function request(self, data, callback) + ID = ID + 1 + 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) + BUF[ID] = { + callback = callback, + timeout = os.clock() + TIMEOUT, + } + 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] + log.warn('Recieve id not found: ', table.dump(proto)) + if not data then + return + end + BUF[id] = nil + if os.clock() > data.timeout then + log.warn('Recieve timeout: ', table.dump(proto.error)) + return + end + if proto.result then + data.callback(proto.result) + else + log.warn('Recieve: ', table.dump(proto.error)) + end +end + +return { + notify = notify, + request = request, + response = response, + recieve = recieve, +} |