openresty中使用lua-nginx创建socket实例
时间:2021-07-02 08:55:21|栏目:|点击: 次
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)
完美运行:

上一篇:最近ISA服务器出现无法打开网页(错误代码64错误)的解决方法
栏 目:
下一篇:docker 容器上编译 go 程序提示找不到文件问题
本文标题:openresty中使用lua-nginx创建socket实例
本文地址:http://www.codeinn.net/misctech/151126.html






