Use lua-nginx in openresty to create a socket instance
This article mainly introduces how to use lua-nginx to create a socket instance in openresty. This article provides the code instance and running effect. For more information, see
The Lua language is so powerful, at least I think so. The original Lua does not have the Socket function. You need to download the Lua socket component and require it. The lua-nginx module comes with the socket function and is in the non-blocking mode of 100%. Thanks again to Chapter Yichun.
The use of the socket function is very simple. There are only a few simple methods, there are mainly differences between TCP and UDP. (This is only the lua file. For more information, see the Hello world article)
The Code is as follows:
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 ('* ')
If not line then
Ngx. say ('failed' to read a line', err)
Return
End
Ngx. print (line)
Perfect run: