Use lua-nginx in openresty to create a socket instance

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.