Skip to content

Feature request: dynamic listen/close socket in lua #1690

Open
@rainingmaster

Description

@rainingmaster

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:

  1. 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
  1. 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).

  2. This should be like ngx.timer, can use in each phase. If run it in init_by_lua, all worker will bind same address by reuseport.

  3. Different worker can bind same address in different time by reuseport.

  4. When the worker exit, all listen will close automatic.

  5. A new independent phase should be build(like timer, maybe name as lua_socket?), some function, such as ngx.req.* can not be use.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions