openresty中使用lua-nginx創(chuàng)建socket實例
更新時間:2015年04月20日 09:27:21 投稿:junjie
這篇文章主要介紹了openresty中使用lua-nginx創(chuàng)建socket實例,本文直接給出代碼實例和運行效果,需要的朋友可以參考下
Lua語言太強大了,至少我是這樣覺得的。原始的Lua沒有Socket功能,需要使用者下載Lua socket組件,require一下才行。而lua-nginx模塊自帶了socket功能,而且是100%的非阻塞模式,再次感謝作者章亦春。
使用socket功能很簡單,只有幾個簡單的方法即可主要就是有TCP和UDP的區(qū)別。(這里只是lua文件,其他請見Hello world 文章)
復(fù)制代碼 代碼如下:
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)
完美運行:
相關(guān)文章
Lua編程示例(一):select、debug、可變參數(shù)、table操作、error
這篇文章主要介紹了Lua編程示例(一):select、debug、可變參數(shù)、table操作、error,本文直接給出代碼實例,需要的朋友可以參考下2015-07-07Lua中的變量類型與語句學(xué)習(xí)總結(jié)
這篇文章主要介紹了Lua中的變量類型與語句學(xué)習(xí)總結(jié),總結(jié)了Lua入門過程中的一些基礎(chǔ)知識,需要的朋友可以參考下2016-06-06Cocos2d-x中調(diào)用Lua及HelloWorld.lua源碼分解
這篇文章主要介紹了Cocos2d-x中調(diào)用Lua及HelloWorld.lua源碼分解,本文最后總結(jié)了一些Lua的語法,需要的朋友可以參考下2014-09-09