Create socket instance using Lua-nginx in Openresty

Source: Internet
Author: User
Tags lua socket

This article mainly introduces the use of Lua-nginx in openresty to create a socket instance, this article directly gives code examples and running effects, need friends can refer to the following

The LUA language is too powerful, at least that's how I feel. The original LUA does not have a socket function and requires the user to download the LUA socket component for a require. and the Lua-nginx module with the socket function, and is 100% non-blocking mode, thanks again to the author Zhang Yichun.

The use of the socket function is very simple, only a few simple methods can be mainly the difference between TCP and UDP. (This is just a LUA file, others see Hello World article)

The code is as follows:

Local sock = Ngx.socket.tcp ()

Local Ok,err = Sock:connect (' ', 43)

If not OK then

Ngx.say (' Failed to connect whois server ', err)



Sock:settimeout (5000)

Local OK, err = Sock:send ("Baidu.cnrn")

If not OK then

Ngx.say (' Failed to send data to WHOIS server ', err)



Local line, err, partial = sock:receive (' *a ')

If not line then

Ngx.say (' Failed to read a line ', err)



Ngx.print (line)

Perfect operation:

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: 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.