openresty中使用lua-nginx创建socket实例

这篇文章主要介绍了openresty中使用lua-nginx创建socket实例,本文直接给出代码实例和运行效果,需要的朋友可以参考下

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)

完美运行:


以上就是openresty中使用lua-nginx创建socket实例的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Lua