openresty中使用lua-nginx建立socket執行個體_Lua

來源:互聯網
上載者:User

Lua語言太強大了,至少我是這樣覺得的。原始的Lua沒有Socket功能,需要使用者下載Lua socket組件,require一下才行。而lua-nginx模組內建了socket功能,而且是100%的非阻塞模式,再次感謝作者章亦春。

使用socket功能很簡單,只有幾個簡單的方法即可主要就是有TCP和UDP的區別。(這裡只是lua檔案,其他請見Hello world 文章)

複製代碼 代碼如下:

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)
local ok, err = sock:send("baidu.cn\r\n")
if not ok then
 ngx.say('Failed to send data to whois server', err)
 return
end
local line, err, partial = sock:receive('*a')
if not line then
 ngx.say('Failed to read a line', err)
 return
end
ngx.print(line)

完美運行:


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.