openresty中使用lua-nginx創(chuàng)建socket實(shí)例

字號(hào):


    這篇文章主要介紹了openresty中使用lua-nginx創(chuàng)建socket實(shí)例,本文直接給出代碼實(shí)例和運(yùn)行效果,需要的朋友可以參考下
    Lua語(yǔ)言太強(qiáng)大了,至少我是這樣覺(jué)得的。原始的Lua沒(méi)有Socket功能,需要使用者下載Lua socket組件,require一下才行。而lua-nginx模塊自帶了socket功能,而且是100%的非阻塞模式,再次感謝作者章亦春。
    使用socket功能很簡(jiǎn)單,只有幾個(gè)簡(jiǎn)單的方法即可主要就是有TCP和UDP的區(qū)別。(這里只是lua文件,其他請(qǐng)見(jiàn)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.cnrn")
    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)行: