reuse udp socket in ngx.timer

43 views
Skip to first unread message

Nicolas Adrian

unread,
May 12, 2022, 9:01:54 AM5/12/22
to openresty-en
I tried to create only one ngx.socket.udp in an init_worker_by_lua_block as follows:

init_worker_by_lua_block {
  local function init_statsd()
      local sock = ngx.socket.udp()
      udp:setpeername("myhost", 8125)
      -- flush the statsd buffer
      local ok, err = ngx.timer.every(1, statsd.flush, sock)
      if not ok then
          ngx.log(ngx.ERR, "failed to create periodic statsd timer: ", err)
      end
  end

  local ok, err = ngx.timer.at(0, init_statsd)
  if not ok then
      ngx.log(ngx.ERR, "failed to create init_statsd timer: ", err)
  end
}

However, I get an error:  attempt to send data closed on a socket

It seems like the socket created in the ngx.timer.at callback is destroyed or closed automatically.
Thus, am I forced to recreate a udp socket for each call in ngx.timer.every callback ?

Nicolas Adrian

unread,
May 12, 2022, 9:06:18 AM5/12/22
to openresty-en
edit: the error is actually attempt to send data on a closed socket

Junlong Li

unread,
May 18, 2022, 6:09:32 AM5/18/22
to openresty-en
Yes, you need to recreate the udp socket for each call in ngx.timer.every callback.
Reply all
Reply to author
Forward
0 new messages