+function Daemon.dprint(self, msg)
+ if self.debug then
+ io.stderr:write("[daemon] " .. msg .. "\n")
+ end
+end
+
+function Daemon.register(self, sock, clhandler, errhandler)
+ table.insert( self.reading, sock )
+ self.handler[sock] = { clhandler = clhandler, errhandler = errhandler }
+end
+
+function Daemon.run(self)
+ while true do
+ self:step()
+ end
+end
+
+function Daemon.step(self)
+ local input, output, err = socket.select( self.reading, nil, 0 )
+ local working = false
+
+ -- accept new connections
+ for i, connection in ipairs(input) do
+
+ local sock = connection:accept()
+
+ if sock then
+ -- check capacity
+ if not self.threadlimit or self.threadc < self.threadlimit then
+
+ if self.debug then
+ self:dprint("Accepted incoming connection from " .. sock:getpeername())
+ end
+
+ local t = Thread(sock, self.handler[connection].clhandler)
+ self.threads[sock] = t
+ self.threadc = self.threadc + 1
+
+ if self.debug then
+ self:dprint("Created " .. tostring(t))
+ end
+
+ -- reject client
+ else
+ if self.debug then
+ self:dprint("Rejected incoming connection from " .. sock:getpeername())
+ end
+
+ if self.handler[connection].errhandler then
+ self.handler[connection].errhandler( sock )
+ end
+
+ sock:close()
+ end