LuaSocket
Network support for the Lua language

home · download · introduction · reference


Introduction

Communication in LuaSocket is performed via I/O objects. These can represent different network domains. Currently, support is provided for TCP and UDP, but there is work in progress to implement SSL, Local Domain, Pipes, File Descriptors etc. I/O objects provide a standard interface to I/O across different domains and operating systems. LuaSocket 2.0 has been rewritten from scratch to simplify the future addition of new domains.

The LuaSocket API was designed with two goals in mind. First, users experienced with the C API to sockets should feel comfortable using LuaSocket. Second, the simplicity and the feel of the Lua language should be preserved. To achieve these goals, the LuaSocket API keeps the function names and semantics the C API whenever possible, but their usage in Lua has been greatly simplified.

One of the simplifications is the timeout control mechanism. As in C, all I/O operations are blocking by default. For example, the send, receive and accept methods of the TCP domain will block the caller application until the operation is completed (if ever!). However, with a call to the settimeout method, an application can specify upper limits on the time it can be blocked by LuaSocket (the "total" timeout), on the time LuaSocket can internally be blocked by any OS call (the "block" timeout) or a combination of the two. Each LuaSocket call might perform several OS calls, so that the two timeout values are not equivalent.

Another important difference is the receive pattern capability. Applications can read data from stream domains (such as TCP) line by line, block by block, or until the connection is closed. All I/O reads are buffered and the performance differences between different receive patterns are negligible.

Finally, the host name resolution is transparent, meaning that most functions and methods accept both IP addresses and host names. In case a host name is given, the library queries the system's resolver and tries the main returned IP address. Note that direct use of IP addresses is more efficient, of course. The toip and tohostname functions from the DNS module are provided to convert between host names and IP addresses.

Previous versions of LuaSocket provided global functions for operating on I/O objects. To give the library a Lua 5.0 feel, these have been eliminated from LuaSocket 2.0. I/O operations are only available as methods of the corresponding I/O objects. Naturally, different I/O objects accept different operations. The core functionality for TCP and UDP objects is introduced in the following sections, following a few words about initialization.

Initializing the library

Beginning with version 2.0 and following the Lua 5.0 trend, all LuaSocket functionality is defined inside a table (or rather a namespace) stored with the global name socket. To have this table created and its contents made available to a Lua script, the interpreter running the script must be linked to the LuaSocket library, and to whatever libraries the host OS requires for network access (Windows requires ws2_32.lib, for instance). LuaSocket is initialized in the Lua state given as the argument to the function luaopen_socket, the only C function exported by the library. After initialization, scripts are free to use all of the LuaSocket API.

TCP

TCP (Transfer Control Protocol) is reliable stream protocol. In other words, applications communicating through TCP can send and receive data as an error free stream of bytes. Data is split in one end and reassembled transparently on the other end. There are no boundaries in the data transfers. The library allows users to read data from the sockets in several different granularity: patterns are available for lines, arbitrary sized blocks or "read up to connection closed", all with good performance.

The library distinguishes three types of TCP sockets: master, client and server sockets.

Master sockets are newly created TCP sockets returned by the function socket.tcp. A master socket is transformed into a server socket after it is associated with a local address by a call to the bind method. Conversely, it can be changed into a client socket with the method connect, that associates it with a remote address.

On server sockets, applications can use the accept method to wait for a client connection. Once a connection is established, a client socket object is returned representing this connection. The other methods available for server socket objects are getsockname, setoption, settimeout and close.

Client sockets are used to exchange data between two applications over the Internet. Applications can call the methods send and receive to send and receive data. The other methods available for client socket objects are getsockname, getpeername, setoption, settimeout and close.

Example:

A simple echo server, using LuaSocket. The program binds to an ephemeral port (one that is chosen by the operating system) on the local host and awaits client connections on that port. When a connection is established, the program reads a line from the remote end and sends it back, closing the connection immediately after. You can test it using the telnet program.

-- create a new TCP object
server, err = socket.tcp()
assert(server, err)
-- bind it to the local host, at any port
ret, err = server:bind("*", 0)
assert(ret, err)
-- find out which port the OS chose for us
ip, port = server:getsockname()
-- print a message informing what's up
print("Please telnet to localhost on port " .. port)
print("After connecting, you have 10s to enter a line to be echoed")
-- loop forever waiting for clients
while 1 do
  -- wait for a conection from any client
  client, err = server:accept()
  -- make sure we don't block waiting for this client's line
  client:settimeout(10)
  -- receive the line
  line, err = client:receive()
  -- if there was no error, send it back to the client
  if not err then 
    client:send(line .. "\n") 
  end
  -- done with client, close the object
  client:close()
end

UDP

UDP (User Datagram Protocol) is a non-reliable datagram protocol. In other words, applications communicating through UDP send and receive data as independent blocks, which are not guaranteed to reach the other end. Even when they do reach the other end, they are not guaranteed to be error free. Data transfers are atomic, one datagram at a time. Reading only part of a datagram discards the rest, so that the following read operation will act on the next datagram. The advantages are in simplicity (no connection setup) and performance (no error checking or error correction).

An UDP socket object is created by the socket.udp function. UDP sockets do not need to be connected before use. The method sendto can be used immediately after creation to send a datagram to IP address and port. Host names are not allowed because performing name resolution for each packet would be forbiddingly slow. Methods receive and receivefrom can be used to retrieve datagrams, the latter returning the IP and port of the sender as extra return values (thus being slightly less efficient).

When communication is performed repeatedly with a single peer, an application should call the setpeername method to specify a permanent partner. Methods sendto and receivefrom can no longer be used, but the method send can be used to send data directly to the peer, and the method receive will only return datagrams originating from that peer. There is about 30% performance gain due to this practice.

To associate an UDP socket with a local address, an application calls the setsockname method before sending any datagrams. Otherwise, the socket is automatically bound to an ephemeral address before the first data transmission and once bound the local address cannot be changed. The other methods available for UDP sockets are getpeername, getsockname, settimeout, setoption and close.

Example:

A simple daytime client, using LuaSocket. The program connects to a remote server and tries to retrieve the daytime, printing the answer it got or an error message.

host = "localhost" -- change here to the host you want to contact
port = port or 13
-- convert host name to ip address
ip, err = socket.dns.toip(host)
assert(ip, err)
-- create a new UDP object
udp = socket.udp()
-- contact daytime host
nsent, err = udp:sendto("anything", ip, port)
assert(not err, err)
-- retrieve the answer
dgram, err = udp:receive()
assert(dgram, err)
-- display to user
print(dgram)