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
|
local uv = require('luv')
local SocketStream = {}
SocketStream.__index = SocketStream
function SocketStream.open(file)
local socket = uv.new_pipe(false)
local self = setmetatable({
_socket = socket,
_stream_error = nil
}, SocketStream)
uv.pipe_connect(socket, file, function (err)
self._stream_error = self._stream_error or err
end)
return self
end
function SocketStream:write(data)
if self._stream_error then
error(self._stream_error)
end
uv.write(self._socket, data, function(err)
if err then
error(self._stream_error or err)
end
end)
end
function SocketStream:read_start(cb)
if self._stream_error then
error(self._stream_error)
end
uv.read_start(self._socket, function(err, chunk)
if err then
error(err)
end
cb(chunk)
end)
end
function SocketStream:read_stop()
if self._stream_error then
error(self._stream_error)
end
uv.read_stop(self._socket)
end
function SocketStream:close()
uv.close(self._socket)
end
return SocketStream
|