lua-nginx-module 內置 **100% 非阻塞 cosocket API** (TCP/UDP),無需外部依賴。本文演示在 OpenResty 中建立 TCP 連接查詢 Whois 服務器,完整代碼與運行效果圖。
ngx.socket.tcp() / ngx.socket.udp():創建 socket 對象。sock:connect(host, port):非阻塞連接。sock:settimeout(ms):設置超時 (毫秒)。sock:send(data):發送數據。sock:receive(pattern):接收數據,'*a' 讀至關閉,'*l' 讀行。sock:close():關閉連接 (或依賴 GC)。
-- whois.lua
local sock = ngx.socket.tcp()
local ok, err = sock:connect("whois.cnnic.net.cn", 43)
if not ok then
ngx.say("Failed to connect whois server: ", err)
return
end
sock:settimeout(5000) -- 5秒超時
local query = "baidu.cn\r\n"
local ok, err = sock:send(query)
if not ok then
ngx.say("Failed to send data: ", err)
return
end
local line, err, partial = sock:receive("*a") -- 讀取所有直到關閉
if not line then
ngx.say("Failed to read response: ", err)
return
end
ngx.print(line) -- 直接輸出原始響應
location /whois {
default_type text/plain;
content_by_lua_file /opt/lua/bin/whois.lua;
}

頁面直接顯示 baidu.cn 的 Whois 記錄信息,含註冊商、創建/過期時間、DNS 服務器等。
sock:setkeepalive() 歸還連接池復用,極大降低握手開銷。sock:sslhandshake() 升級 TLS。
local sock = ngx.socket.udp()
sock:setpeername("127.0.0.1", 514)
sock:send("<134>Test log message from OpenResty")
OpenResty cosocket 將 **Nginx 事件驅動模型** 與 **Lua 協程** 完美融合,**同步寫法、異步執行**,是構建高性能網關、代理、聚合服務的利器。Whois 查詢僅是冰山一角,更多場景:上游服務健康檢查、認證授權轉發、實時數據推流、协议轉換網關等。