Created
November 30, 2010 07:26
-
-
Save zeen/721298 to your computer and use it in GitHub Desktop.
lua-ev emulation using socket.select
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- lua-ev emulation using socket.select | |
local READ, WRITE = 0x01, 0x02; | |
local timeout = 5; | |
local Loop = {}; | |
function Loop.new() | |
print("Loop:new") | |
local loop = { reading = {}, writing = {} }; | |
function loop:loop() | |
local reading, writing = self.reading, self.writing; | |
print("loop:loop") | |
while #reading + #writing > 0 do | |
local readable, writable, err = socket.select(reading, writing, timeout); | |
print("select says:", #readable, #writable, err) | |
for i=1,#readable do | |
local io = readable[i]; | |
if reading[io] then | |
local revents = READ; if writable[io] then revents = revents+WRITE; end | |
io.on_io(self, io, revents); | |
end | |
end | |
for i=1,#writable do | |
local io = writable[i]; | |
if writing[io] and not readable[io] then | |
io.on_io(self, io, WRITE); | |
end | |
end | |
end | |
end | |
return loop; | |
end | |
local IO = {}; | |
function IO.new(on_io, file_descriptor, revents) | |
print("IO.new") | |
local io = { READ = revents % 2 == 1, WRITE = revents % 4 >= 2, fd = file_descriptor, on_io = on_io }; | |
function io:start(loop, is_daemon) | |
print("io:start") | |
local function add(self, list) | |
if not list[self] then | |
local n = #list + 1; | |
list[self], list[n] = n, self; | |
end | |
end | |
local function remove(self, list) | |
if list[self] then | |
list[list[self]] = nil; -- TODO shift | |
list[self] = nil; | |
end | |
end | |
if self.READ then add(self, loop.reading); end | |
if self.WRITE then add(self, loop.writing); end | |
end | |
function io:stop(loop) | |
error("io:stop") | |
remove(self, loop.reading); | |
remove(self, loop.writing); | |
end | |
function io:getfd() return file_descriptor; end | |
return io; | |
end | |
return { Loop = Loop, IO = IO, READ = READ, WRITE = WRITE }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment