mirror of
https://github.com/cloudwu/skynet.git
synced 2026-07-22 11:03:12 +00:00
simplify clientsocket lib
This commit is contained in:
@@ -2,30 +2,47 @@ package.cpath = "luaclib/?.so"
|
||||
|
||||
local socket = require "clientsocket"
|
||||
local cjson = require "cjson"
|
||||
local bit32 = require "bit32"
|
||||
|
||||
local fd = socket.connect("127.0.0.1", 8888)
|
||||
local fd = assert(socket.connect("127.0.0.1", 8888))
|
||||
|
||||
local last
|
||||
local result = {}
|
||||
local function send_package(fd, pack)
|
||||
local size = #pack
|
||||
local package = string.format("%c%c%s",
|
||||
bit32.extract(size,8,8),
|
||||
bit32.extract(size,0,8),
|
||||
pack)
|
||||
|
||||
local function dispatch()
|
||||
while true do
|
||||
local status
|
||||
status, last = socket.recv(fd, last, result)
|
||||
if status == nil then
|
||||
error "Server closed"
|
||||
end
|
||||
if not status then
|
||||
break
|
||||
end
|
||||
for _, v in ipairs(result) do
|
||||
local session,t,str = string.match(v, "(%d+)(.)(.*)")
|
||||
assert(t == '-' or t == '+')
|
||||
session = tonumber(session)
|
||||
local result = cjson.decode(str)
|
||||
print("Response:",session, result[1], result[2])
|
||||
end
|
||||
socket.send(fd, package)
|
||||
end
|
||||
|
||||
local function unpack_package(text)
|
||||
local size = #text
|
||||
if size < 2 then
|
||||
return nil, text
|
||||
end
|
||||
local s = text:byte(1) * 256 + text:byte(2)
|
||||
if size < s+2 then
|
||||
return nil, text
|
||||
end
|
||||
|
||||
return text:sub(3,2+s), text:sub(3+s)
|
||||
end
|
||||
|
||||
local function recv_package(last)
|
||||
local result
|
||||
result, last = unpack_package(last)
|
||||
if result then
|
||||
return result, last
|
||||
end
|
||||
local r = socket.recv(fd)
|
||||
if not r then
|
||||
return nil, last
|
||||
end
|
||||
if r == "" then
|
||||
error "Server closed"
|
||||
end
|
||||
return unpack_package(last .. r)
|
||||
end
|
||||
|
||||
local session = 0
|
||||
@@ -33,12 +50,25 @@ local session = 0
|
||||
local function send_request(v)
|
||||
session = session + 1
|
||||
local str = string.format("%d+%s",session, cjson.encode(v))
|
||||
socket.send(fd, str)
|
||||
send_package(fd, str)
|
||||
print("Request:", session)
|
||||
end
|
||||
|
||||
local last = ""
|
||||
|
||||
while true do
|
||||
dispatch()
|
||||
while true do
|
||||
local v
|
||||
v, last = recv_package(last)
|
||||
if not v then
|
||||
break
|
||||
end
|
||||
local session,t,str = string.match(v, "(%d+)(.)(.*)")
|
||||
assert(t == '-' or t == '+')
|
||||
session = tonumber(session)
|
||||
local result = cjson.decode(str)
|
||||
print("Response:",session, result[1], result[2])
|
||||
end
|
||||
local cmd = socket.readstdin()
|
||||
if cmd then
|
||||
local args = {}
|
||||
|
||||
Reference in New Issue
Block a user