Description
Hi there,
I think many user need the new feature that we can dynamic listen or close a socket in the lua context, such as the discuss here, or some user' PR #1393 .
About the usage of this function, I have some ideas:
- The usage should like this:
function accept_hook(socket)
local b, err = sock:receive(8) -- like ngx.tcp.socket/ngx.udp.socket, it is a stream-typed cosocket
if err then
return
end
sock:send("welcome")
ngx.exit() -- close the socket for tcp
end
local err = ngx.socket.listen("tcp://127.0.0.1:5050", accept_hook) -- can not bind same address more than one time
if err then
ngx.log(ngx.ERR, "listen failed")
return
end
And support close the listen by the address, like this:
local err = ngx.socket.close("tcp://127.0.0.1:5050")
if err then
ngx.log(ngx.ERR, "listen failed")
return
end
-
ngx.socket.listen
for TCP, will bind, listen and accept a socket, and put the socekt into event list, like ngx_event_accept, and for UDP, will bind and recvmsg for the socket, like [ngx_event_recvmsg], and put the socekt into event list(https://github.com/nginx/nginx/blob/master/src/event/ngx_event_udp.c#L32). -
This should be like
ngx.timer
, can use in each phase. If run it ininit_by_lua
, all worker will bind same address by reuseport. -
Different worker can bind same address in different time by reuseport.
-
When the worker exit, all listen will close automatic.
-
A new independent phase should be build(like
timer
, maybe name aslua_socket
?), some function, such asngx.req.*
can not be use.