luvit/luv

Why udp_recv_start callback call twice?

cc-hng opened this issue · 2 comments

cc-hng commented

I wrote a udp server/client sample as below, the callback of server:recv_start called twice.

local uv = require("luv")
local inspect = require("inspect")

function set_interval(interval, callback)
	local timer = uv.new_timer()
	uv.timer_start(timer, interval, interval, function()
		callback(timer)
	end)
	return timer
end

local server = uv.new_udp()
server:bind("0.0.0.0", 9124, { reuseaddr = true })
server:recv_start(function(err, data, addr, flags)
  -- assert(not err, err)
  -- assert(data == "PING")
  print(inspect { err, data, addr, flags })
  -- uv.close(server)
end)

local client = uv.new_udp()
set_interval(3000, function()
	client:send("PING", "127.0.0.1", 9124, function(err) end)
end)

uv.run()

log

{
  [2] = "PING",
  [3] = {
    family = "inet",
    ip = "127.0.0.1",
    port = 39178
  },
  [4] = {}
}
{
  [4] = {}
}

When data is nil, that's to signal that the stream is exhausted and you can/should close the connection. I believe it is because your client connection is not kept alive, but I'm not sure. Look at the luv readme for a working server/client echo.

cc-hng commented

Thanks a lot, I have found an answer from the libuv/help
libuv/help#89 (comment)