openresty中使用lua-nginx创建socket实例
更新时间:2015年04月20日 09:27:21 投稿:junjie
这篇文章主要介绍了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)
完美运行:
相关文章
Lua编程示例(一):select、debug、可变参数、table操作、error
这篇文章主要介绍了Lua编程示例(一):select、debug、可变参数、table操作、error,本文直接给出代码实例,需要的朋友可以参考下2015-07-07Cocos2d-x中调用Lua及HelloWorld.lua源码分解
这篇文章主要介绍了Cocos2d-x中调用Lua及HelloWorld.lua源码分解,本文最后总结了一些Lua的语法,需要的朋友可以参考下2014-09-09
最新评论