首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

OpenResty lua-nginx-module 非阻塞 Socket 實戰:TCP Whois 查詢

     編輯:更多程式設計知識

lua-nginx-module 內置 **100% 非阻塞 cosocket API** (TCP/UDP),無需外部依賴。本文演示在 OpenResty 中建立 TCP 連接查詢 Whois 服務器,完整代碼與運行效果圖。

核心 API

  • 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)。

完整 Lua 代碼


-- 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)  -- 直接輸出原始響應

Nginx 配置掛載


location /whois {
    default_type text/plain;
    content_by_lua_file /opt/lua/bin/whois.lua;
}

運行效果

Whois 查詢結果頁面

頁面直接顯示 baidu.cn 的 Whois 記錄信息,含註冊商、創建/過期時間、DNS 服務器等。

關鍵優勢

  • 非阻塞:單 Worker 可並發處理數千 Socket 連接,不阻塞 Nginx 事件循環。
  • 語法簡潔:同步風格代碼,無回調地獄。
  • 連接池:sock:setkeepalive() 歸還連接池復用,極大降低握手開銷。
  • SSL 支持:sock:sslhandshake() 升級 TLS。

UDP 示例 (syslog 發送)


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 查詢僅是冰山一角,更多場景:上游服務健康檢查、認證授權轉發、實時數據推流、协议轉換網關等。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved