Skip to content

Instantly share code, notes, and snippets.

@outsinre
Created September 28, 2023 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save outsinre/69b3ff0a5c35360f29448e5643ca1bad to your computer and use it in GitHub Desktop.
Save outsinre/69b3ff0a5c35360f29448e5643ca1bad to your computer and use it in GitHub Desktop.
Reuse cosocket after close
local pl_pretty = require("pl.pretty").write
-- create cosocket
local sock = ngx.socket.tcp()
sock:settimeouts(1000, 15000, 15000)
ngx.say("sock 1 = ", pl_pretty(sock))
-- create kernel socket
local ok, err = sock:connect("8.8.8.8", 53)
if not ok then
ngx.say("connection err: ", err)
end
ngx.say("sock 2 = ", pl_pretty(sock))
-- create a new kernel socket
ok, err = sock:connect("1.1.1.1", 53)
if not ok then
ngx.say("connection err: ", err)
end
ngx.say("sock 3 = ", pl_pretty(sock))
-- ss -npeat dst "8.8.8.8" or dst "1.1.1.1"
-- ll /proc/<pid>/fd
ngx.sleep(30)
-- only discard kernel socket
ngx.say("discard kernel sockets")
sock:close()
-- cosocket remains
ngx.say("sock 4 = ", pl_pretty(sock))
-- ss -npeat dst "8.8.8.8" or dst "1.1.1.1"
ngx.sleep(60)
@outsinre
Copy link
Author

  1. close() only discard kernel socket (TCP connection) but preserve cosocket itself.
  2. setkeepalive preserve kernel socket (TCP connection) as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment