mirror of
https://github.com/cloudwu/skynet.git
synced 2026-07-25 04:33:05 +00:00
82 lines
1.4 KiB
Lua
82 lines
1.4 KiB
Lua
local socket = require "socket"
|
|
|
|
local readbytes = socket.read
|
|
local writebytes = socket.write
|
|
|
|
local sockethelper = {}
|
|
local socket_error = setmetatable({} , { __tostring = function() return "[Socket Error]" end })
|
|
|
|
sockethelper.socket_error = socket_error
|
|
|
|
local function preread(fd, str)
|
|
return function (sz)
|
|
if str then
|
|
if sz == #str or sz == nil then
|
|
local ret = str
|
|
str = nil
|
|
return ret
|
|
else
|
|
if sz < #str then
|
|
local ret = str:sub(1,sz)
|
|
str = str:sub(sz + 1)
|
|
return ret
|
|
else
|
|
sz = sz - #str
|
|
local ret = readbytes(fd, sz)
|
|
if ret then
|
|
return str .. ret
|
|
else
|
|
error(socket_error)
|
|
end
|
|
end
|
|
end
|
|
else
|
|
local ret = readbytes(fd, sz)
|
|
if ret then
|
|
return ret
|
|
else
|
|
error(socket_error)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
function sockethelper.readfunc(fd, pre)
|
|
if pre then
|
|
return preread(fd, pre)
|
|
end
|
|
return function (sz)
|
|
local ret = readbytes(fd, sz)
|
|
if ret then
|
|
return ret
|
|
else
|
|
error(socket_error)
|
|
end
|
|
end
|
|
end
|
|
|
|
sockethelper.readall = socket.readall
|
|
|
|
function sockethelper.writefunc(fd)
|
|
return function(content)
|
|
local ok = writebytes(fd, content)
|
|
if not ok then
|
|
error(socket_error)
|
|
end
|
|
end
|
|
end
|
|
|
|
function sockethelper.connect(host, port)
|
|
local fd = socket.open(host, port)
|
|
if fd then
|
|
return fd
|
|
end
|
|
error(socket_error)
|
|
end
|
|
|
|
function sockethelper.close(fd)
|
|
socket.close(fd)
|
|
end
|
|
|
|
return sockethelper
|