LUA Development Notes

Source: Internet
Author: User

Because of the recent project needs, learning LUA programming and using LUA for network-related development, here is a record of the relevant knowledge.

Throughout the project, I was only responsible for the development of the firmware upgrade module, the data format is custom, and is not in JSON or XML, mainly because the transfer of the field is relatively small, and do not want to introduce too many third-party libraries.

First, Luasocket

In the project, TCP communication is used, and only TCP-related knowledge is introduced here.

1. The socket module needs to be loaded first:

Local socket = require (' socket ')

If you want to view the version of Luasocket:

Print (' Luasocket ver: ', socket._version)

2. TCP Common methods:

As to the following methods, I feel that the official documentation has been made clear, and the official notes are directly quoted here:

1)socket. bind (address, port [, backlog])

Create a TCP server object bind to (address, port), which is used for the listen function. Familiar with the socket programming under Linux, you will find these are familiar. This function returns a TCP server object if it fails to return nil.

2)server:accept ()

Waits for a remote connection on the server object and returns a client object representing that connection.

3)client:getsockname (): get socket IP and port

4) Server:getpeername (): Get IP with port on peer

5)client:receive ([pattern [, prefix]])

receive data, pattern similar to LUA file I/O format, with values such as:

' *all ', ' *a ': reads from the socket until the connection is closed. No end-of-line translation is performed;

' *line ', ' *l ': reads a line of text from the socket. The line was terminated by a LF character (ASCII ten), optionally preceded by a CR character (ASCII 13). The CR and LF characters is not included on the returned line. In fact, all CR characters is ignored by the pattern. This is the default pattern;

Number: causes the method to read a specified number of bytes from the socket.

if successful, the method returns the received pattern.

in Case of error, the method returns  Nil  followed by a error message which can be the string ' closed timeout  

6) client:Send (data [, I [, J]])

sends data through client object.

    data is the string to is sent. The optional arguments  i and  J  lua function to allow the selection of a substring to be sent.

If Successful, the method returns the index of the last byte within [I, J] That has been sent.

in case of error, the method returns Nil , followed by a error message,followed by the index of the last byte within [I, J] That has been sent.

7) client:Close () : closes a TCP object.

8)master:settimeout (value [, mode])

Changes the timeout values for the object. By default, all I/O operations is blocking.

9) server:setoption (option [, value])

sets options for the TCP object. Options is needed by low-level or time-critical applications.

As we commonly use: ' KeepAlive ', ' reuseaddr ', ' Tcp-nodelay '

Master:connect(address, Port) : Used to initiate a connection request for the user Client

The following code shows the approximate structure of the TCP server and the client, respectively:

-- echo serverlocal socket = require (' socket ') local serv = socket.bind (' * ',  8000)  -- bind to any ip and 8000 port.if not serv  thenprint (' Bind error ') os.exit ( -1) endwhile true doprint (' begin accept ') local  Client = serv:accept () if not client thenprint (' accept failed ') os.exit (-1) Endlocal peer_ip, peer_port = client:getpeername () Print (String.Format (' handle %s:%d  request begin ',  peer_ip, peer_port)) While true dolocal data, err  = client:receive (' *line ')  -- read one line dataif not err  Then    print (' data:  ',  data)     client:send (data)  --  send data back to clientelse    print (' err:  ',  err)     breakendEndclient:close () End 

-- echo clientlocal socket = require (' socket ') local client =  Socket.connect (' localhost ',  8000)  -- connect to localhost:8000if not client  thenprint (' connect failed ') os.exit ( -1) endwhile true do    local  Data = io.read (' *line ')     if not data then         print (' EOF ')         break     end        client:send (data)     local  resp, err, partial = client:receive ()     if not err  then        print (' receive:  ',  RESP)      else        print (' err:  ',  err)          break    endendclient:close () 


Second, Lua bit operation module

The LUA language itself does not provide a bitwise operation, and a third-party module is required to perform bitwise operations.

Local bit = require (' bit ')

y = Bit.band (x1 [, X2 ...]): Bitwise AND

y = Bit.bor (x1 [, X2 ...]): Bitwise OR

y = Bit.bxor (x1 [, X2 ...]): Bitwise XOR

y = Bit.bnot (x): bitwise inverse

y = bit.lshift (x, N): Logical left Shift

y = bit.rshift (x, N): Logical Right Shift

y = bit.arshift (x, N): Arithmetic right shift

Because I need to pass integers in the project, I need to transfer the integer to the lower position before the high, so we need to use the shift operation.

Third, some methods used by the string module

because the data format in the project is customized, a fixed-size header exists in order to solve the problem of sticky packets for TCP. For example, our heads are:

uin8_t head[4]; head[0] = 0xa5; Head framehead[1] = 0x1l; cmd_iduint16_t len = 0x0010;head[2] = len & 0xff; Low byte of lenhead[3] = Len >> 8; Hight byte of Len

So how do we get this 4-byte hair out in Lua? You can use the following method:String.char ()

Local Len = 0x0010local t = {0xa5, 0x1, Bit.band (Len, 0xff), Bit.rshift (Len, 8)}local data = String.char (unpack (t)) client: Send (data)

So the receiver, when receiving the data header, how to parse it? string.byte ()

Local req, err = client:receive (4) If not err then local req_t = {String.byte (req, 1,-1)} local frame = req_t[1] Local cmd_id = req_t[2] Local len = req_t[3] + bit.lshift (req_t[4], 8) print (String.Format (' frame:%02x, cmd_id:%02x , len:%d ', frame, cmd_id, Len) Else print (' err: ', err) client:close () end


PS: Learn about LUA programming, you can refer to the "LUA programming" book, there is a blog Lua step by step, the content is written according to this, writing very good, http://www.cnblogs.com/stephen-liu74/ Archive/2012/07/30/2487201.html

This will be recorded today, followed by additional additions if necessary.

LUA Development Notes

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.