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

(编辑:jimmy 日期: 2024/10/5 浏览:2)

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实例

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。