openresty中使用lua-nginx創(chuàng)建socket實(shí)例
Lua語言太強(qiáng)大了,至少我是這樣覺得的。原始的Lua沒有Socket功能,需要使用者下載Lua socket組件,require一下才行。而lua-nginx模塊自帶了socket功能,而且是100%的非阻塞模式,再次感謝作者章亦春。
使用socket功能很簡(jiǎn)單,只有幾個(gè)簡(jiǎn)單的方法即可主要就是有TCP和UDP的區(qū)別。(這里只是lua文件,其他請(qǐng)見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)
完美運(yùn)行:
相關(guān)文章
Lua編程示例(一):select、debug、可變參數(shù)、table操作、error
這篇文章主要介紹了Lua編程示例(一):select、debug、可變參數(shù)、table操作、error,本文直接給出代碼實(shí)例,需要的朋友可以參考下2015-07-07Lua中的變量類型與語句學(xué)習(xí)總結(jié)
這篇文章主要介紹了Lua中的變量類型與語句學(xué)習(xí)總結(jié),總結(jié)了Lua入門過程中的一些基礎(chǔ)知識(shí),需要的朋友可以參考下2016-06-06Lua中關(guān)于元方法的一些知識(shí)點(diǎn)小結(jié)
這篇文章主要介紹了Lua中關(guān)于元方法的一些知識(shí)點(diǎn)小結(jié),本文講解了兩個(gè)具有不同元表的值進(jìn)行算術(shù)操作、關(guān)系類的元方法、保護(hù)元表,需要的朋友可以參考下2014-09-09Cocos2d-x中調(diào)用Lua及HelloWorld.lua源碼分解
這篇文章主要介紹了Cocos2d-x中調(diào)用Lua及HelloWorld.lua源碼分解,本文最后總結(jié)了一些Lua的語法,需要的朋友可以參考下2014-09-09