2023-08-27 14:24:24 (UTC-03:00)
Marcel Rodrigues <marcelgmr@gmail.com>
tcp: refactor to reduce repetition
diff --git a/lib/ludweb/tcp.lua b/lib/ludweb/tcp.lua index 33c2fb9..2634fb9 100644 --- a/lib/ludweb/tcp.lua +++ b/lib/ludweb/tcp.lua @@ -121,9 +121,10 @@ function TCP:run() nfds = C.epoll_wait(efd, evs, curfds, -1) -- the loop below will run zero times if nfds < 1, ignoring errors for n = 0, nfds-1 do - if evs[n].data.fd == self.sockfd then + local readyfd = evs[n].data.fd + if readyfd == self.sockfd then while true do - local newfd = C.accept(self.sockfd, nil, nil) + local newfd = C.accept(readyfd, nil, nil) if newfd == -1 then break end set_non_blocking(newfd) ev[0].events = bit.bor(C.EPOLLIN, C.EPOLLET) @@ -134,7 +135,7 @@ function TCP:run() else local can_close = false while true do - local size = C.recv(evs[n].data.fd, buffer, buflen, 0) + local size = C.recv(readyfd, buffer, buflen, 0) if size == -1 then break elseif size == 0 then @@ -147,7 +148,7 @@ function TCP:run() if dataout == nil then running = false else - C.send(evs[n].data.fd, dataout, #dataout, 0) + C.send(readyfd, dataout, #dataout, 0) end if not keep_alive then can_close = true @@ -157,9 +158,9 @@ function TCP:run() end end if can_close then - C.epoll_ctl(efd, C.EPOLL_CTL_DEL, evs[n].data.fd, ev) - C.shutdown(evs[n].data.fd, C.SHUT_RDWR) - C.close(evs[n].data.fd) + C.epoll_ctl(efd, C.EPOLL_CTL_DEL, readyfd, ev) + C.shutdown(readyfd, C.SHUT_RDWR) + C.close(readyfd) curfds = curfds - 1 end end