socket
The socket namespace contains the core functionality of LuaSocket.
To obtain the socket namespace, run:
-- loads the socket module
local socket = require("socket")
client
client:close() | As in #server.bind. |
client:getpeername() | Returns information about the remote side of a connected client object. |
client:getsockname() | As in #server.getsockname. |
client:getstats() | As in #server.getstats. |
client:receive(pattern, prefix) | Reads data from a client object, according to the specified read pattern. |
client:send(data, i, j) | Sends data through client object. |
client:setoption(option, value) | As in #server.setoption. |
client:setstats(received, sent, age) | As in #server.setstats. |
client:settimeout(value, mode) | As in #server.settimeout. |
client:shutdown(mode) | Shuts down part of a full-duplex connection. |
connected
connected:close() | As in #unconnected.close. |
connected:getpeername() | Retrieves information about the peer associated with a connected UDP object. |
connected:getsockname() | As in #unconnected.getsockname. |
connected:receive(size) | As in #unconnected.receive. |
connected:send(datagram) | Sends a datagram to the UDP peer of a connected object. |
connected:setoption(value) | As in #unconnected.setoption. |
connected:setpeername(address, port) | Changes the peer of a UDP object. |
connected:settimeout(value) | As in #unconnected.settimeout. |
dns
dns.gethostname() | The standard host name
|
dns.tohostname(address) | Converts from IP address to host name. |
dns.toip(address) | Converts from host name to IP address. |
master
master:close() | As in #server.bind. |
master:connect(address, port) | Attempts to connect a master object to a remote host, transforming it into a client object. |
master:getsockname() | As in #server.getsockname. |
master:getstats() | As in #server.getstats. |
master:listen(backlog) | Specifies the socket is willing to receive connections, transforming the object into a server object. |
master:setstats(received, sent, age) | As in #server.setstats. |
master:settimeout(value, mode) | As in #server.settimeout. |
server
server:accept() | Waits for a remote connection on the server object and returns a #client object representing that connection. |
server:close() | Closes a TCP object. |
server:getsockname() | Returns the local address information associated to the object. |
server:getstats() | Returns accounting information on the socket, useful for throttling of bandwidth. |
server:setoption(option, value) | Sets options for the TCP object. |
server:setstats(received, sent, age) | Resets accounting information on the socket, useful for throttling of bandwidth. |
server:settimeout(value, mode) | Changes the timeout values for the object. |
socket
socket._DEBUG | This constant is set to true if the library was compiled with debug support. |
socket._VERSION | This constant has a string describing the current LuaSocket version. |
socket.bind(host, port, backlog_or_hook) | This function is a shortcut that creates and returns a TCP server object bound to a local address and port, ready to accept client connections. |
socket.connect(address, port, locaddr, locport) | This function is a shortcut that creates and returns a TCP client object connected to a remote host at a given port. |
socket.dns | DNS utilities. |
socket.gettime() | Gives time |
socket.newtry(finalizer) | Creates and returns a clean #socket.try function that allows for cleanup before the exception is raised. |
socket.protect(func) | Converts a function that throws exceptions into a safe function. |
socket.select(recvt, sendt, timeout) | Waits for a number of sockets to change status. |
socket.sink(mode, socket) | Creates an LTN12 sink from a stream socket object. |
socket.skip(d, vararg) | Drops a number of arguments and returns the remaining. |
socket.sleep(time) | Freezes the program execution during a given amount of time. |
socket.source(mode, socket) | Creates an LTN12 source from a stream socket object. |
socket.tcp() | Creates and returns a TCP master object. |
socket.try(vararg) | Throws an exception in case of error. |
socket.udp() | Creates and returns an unconnected UDP object. |
unconnected
unconnected:close() | Closes a UDP object. |
unconnected:getsockname() | Returns the local address information associated to the object. |
unconnected:receive(size) | Receives a datagram from the UDP object. |
unconnected:receivefrom(size) | Works exactly as the #unconnected.receive method, except it returns the IP address and port as extra return values (and is therefore slightly less efficient). |
unconnected:sendto(datagram, ip, port) | Sends a datagram to the specified IP address and port number. |
unconnected.setoption(option, value) | Sets options for the UDP object. |
unconnected:setpeername(address, port) | As in #connected.setpeername. |
unconnected:setsockname(address, port) | Binds the UDP object to a local address. |
unconnected:settimeout(value) | Changes the timeout values for the object. |
client
A TCP Client object.
client:close()
client:getpeername()
client:getsockname()
client:getstats()
client:receive(pattern, prefix)
Important note: This function was changed severely. It used to support multiple patterns (but I have never seen this feature used) and now it doesn't anymore. Partial results used to be returned in the same way as successful results. This last feature violated the idea that all functions should return nil on error. Thus it was changed too.
pattern
:
can be any of the following:
prefix
:
(optional) An optional string to be concatenated to the beginning of any received data before return.
Also, after the error message, the function returns the partial result of the transmission.
client:send(data, i, j)
Note: Output is not buffered. For small strings, it is always better to concatenate them in Lua (with the '..' operator) and send the result in one call instead of calling the method several times.
data
:
The string to be sent.
i
:
(optional) As in #string.sub.
j
:
(optional) As in #string.sub.
In case of error, the method returns nil, followed by an error message, followed by the index of the last byte within [i, j] that has been sent. You might want to try again from the byte following that. The error message can be:
client:setoption(option, value)
option
:
value
:
client:setstats(received, sent, age)
received
:
sent
:
age
:
client:settimeout(value, mode)
value
:
mode
:
client:shutdown(mode)
mode
:
Tells which way of the connection should be shut down and can take the value:
#number: This function returns 1.
connected
A connected UDP object.
connected:close()
connected:getpeername()
The IP address and port number of the peer.
connected:getsockname()
connected:receive(size)
size
:
connected:send(datagram)
datagram
:
A #string with the datagram contents. The maximum datagram
size for UDP is 64K minus IP layer overhead. However datagrams larger than the
link layer packet size will be fragmented, which may deteriorate performance
and/or reliability.
connected:setoption(value)
value
:
connected:setpeername(address, port)
Note: Since the address of the peer does not have to be passed to and from the OS, the use of connected UDP objects is recommended when the same peer is used for several transmissions and can result in up to 30% performance gains.
address
:
Can be an IP address or a host name. If address is
'*' and the object is connected, the peer association is removed and the
object becomes an unconnected object again. In that case, the port argument is
ignored.
port
:
The port number.
connected:settimeout(value)
value
:
dns
Name resolution functions return all information obtained from the resolver in a table of the form:
resolved = {
name = canonic-name,
alias = alias-list,
ip = ip-address-list
}
Note that the alias list can be empty.
dns.gethostname()
#string: The standard host name for the machine.
dns.tohostname(address)
address
:
Can be an IP address or host name.
dns.toip(address)
address
:
Can be an IP address or host name.
master
A TCP Master object.
master:close()
master:connect(address, port)
Note: The function socket.connect is available and is a shortcut for the creation of client sockets.
Note: Starting with LuaSocket 2.0, the settimeout method affects the behavior of connect, causing it to return with an error in case of a timeout. If that happens, you can still call socket.select with the socket in the sendt table. The socket will be writable when the connection is established.
address
:
Can be an IP address or a host name.
port
:
Port must be an integer number in the range [1..64K).
master:getsockname()
master:getstats()
master:listen(backlog)
backlog
:
Specifies the number of client connections that can be queued waiting for service.
If the queue is full and another client attempts connection, the connection is refused.
master:setstats(received, sent, age)
received
:
sent
:
age
:
master:settimeout(value, mode)
value
:
mode
:
server
A TCP Server object.
server:accept()
Given error string can be:
server:close()
Note: It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
server:getsockname()
server:getstats()
#number, #number, #number: The number of bytes received, the number of bytes sent, and the age of the socket object in seconds.
server:setoption(option, value)
Note: The given descriptions come from the man pages.
option
:
The option name:
value
:
Depends on the option being set.
server:setstats(received, sent, age)
received
:
Number with the new number of bytes received.
sent
:
Number with the new number of bytes sent.
age
:
is the new age in seconds.
server:settimeout(value, mode)
Note: although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.
Note: The old timeout method is deprecated. The name has been changed for sake of uniformity, since all other method names already contained verbs making their imperative nature obvious.
value
:
The amount of time to wait is specified, in seconds.
The #nil timeout value allows operations to block indefinitely. Negative
timeout values have the same effect.
mode
:
There are two timeout modes and both can be used together for fine tuning:
socket
socket._DEBUG
true
if the library was compiled with debug support.
socket._VERSION
socket.bind(host, port, backlog_or_hook)
host
:
local address to bind to
port
:
local port to bind
backlog_or_hook
:
Optionally, user can also specify the backlog argument to the listen method (defaults to 32).
This third parameter can also be the hook if no backlog parameter is given.
-@param hook is an additional parameter (not compatible with luasocket original socket.bind()
TCP server object
socket.bind("someaddress", 4242, function hook(...) end)
socket.bind("someaddress", 4242, 32,function hook(...) end)
socket.connect(address, port, locaddr, locport)
locaddr
and locport
).
address
:
address to connect to
port
:
port
locaddr
:
optional local address to bind
locport
:
optional local port to bind
TCP client object
socket.dns
socket.gettime()
The time in seconds, relative to the origin of the universe. You should subtract the values returned by this function to get meaningful values.
t = socket.gettime()
-- do stuff
print(socket.gettime() - t .. " seconds elapsed")
socket.newtry(finalizer)
finalizer
is a function that will be called before try throws the exception.
It will be called in protected mode.
The function returns your customized #socket.try function.
Note: This idea saved a lot of work with the implementation of protocols in LuaSocket:
foo = socket.protect(function()
-- connect somewhere
local c = socket.try(socket.connect("somewhere", 42))
-- create a try function that closes 'c' on error
local try = socket.newtry(function() c:close() end)
-- do everything reassured c will be closed
try(c:send("hello there?\r\n"))
local answer = try(c:receive())
...
try(c:send("good bye\r\n"))
c:close()
end)
finalizer
:
function that will be called before try throws the exception.
a customized #socket.try function
socket.protect(func)
func
is a function that calls #socket.try (or assert
, or error
)
to throw exceptions.
Returns an equivalent function that instead of throwing exceptions,
returns nil
followed by an error message.
Note: Beware that if your function performs some illegal operation that raises an error, the protected function will catch the error and return it as a string. This is because the try function uses errors as the mechanism to throw exceptions.
func
:
function that calls #socket.try (or assert
, or error
)
to throw exceptions.
an equivalent function that instead of throwing exceptions,
returns nil
followed by an error message
socket.select(recvt, sendt, timeout)
Recvt
is an array with the sockets to test for characters available
for reading.
Sockets in the sendt
array are watched to see if it is OK
to immediately write on them.
Timeout
is the maximum amount of time (in seconds) to wait for a change
in status. A nil
, negative or omitted timeout
value allows the function
to block indefinitely.
Recvt
and sendt
can also be empty tables or nil
.
Non-socket values (or values with non-numeric indices) in the arrays
will be silently ignored.
The function returns a list with the sockets ready for reading,
a list with the sockets ready for writing and an error message.
The error message is "timeout" if a timeout condition was met and nil
otherwise.
The returned tables are doubly keyed both by integers and also by the sockets
themselves, to simplify the test if a specific socket has changed status.
Important note: a known bug in WinSock causes select to fail on non-blocking TCP sockets. The function may return a socket as writable even though the socket is not ready for sending.
Another important note: calling select with a server socket in the receive parameter before a call to #server.accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever.
Yet another note: If you close a socket and pass it to select, it will be ignored.
recvt
:
an array with the sockets to test for characters available
for reading. Can also be empty table or nil. Non-socket values
(or values with non-numeric indices) in the array will be silently ignored.
sendt
:
an array of sockets that are watched to see if it is OK
to immediately write on them. Can also be empty table or nil. Non-socket values
(or values with non-numeric indices) in the array will be silently ignored.
timeout
:
optional maximum amount of time (in seconds)
to wait for a change in status.
A nil, negative or omitted timeout value allows the function to block indefinitely.
a list with the sockets ready for reading, a list with the sockets ready for writing and an error message.
socket.sink(mode, socket)
mode
:
Defines the behavior of the sink. The following options are available:
socket
:
The stream socket object used to send the data.
A sink with the appropriate behavior.
socket.skip(d, vararg)
Note: This function is useful to avoid creation of dummy variables:
-- get the status code and separator from SMTP server reply
local code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)"))
d
:
The number of arguments to drop.
vararg
:
The arguments.
retd+1 to retn.
socket.sleep(time)
time
:
Number of seconds to sleep for. The function truncates time down to the nearest integer.
socket.source(mode, socket)
mode
:
Defines the behavior of the source. The following options are available:
socket
:
The stream socket object used to receive the data.
A source with the appropriate behavior.
socket.tcp()
socket.try(vararg)
vararg
:
Can be arbitrary arguments, but are usually the return values of a function call nested with try.
-- connects or throws an exception with the appropriate error message
c = socket.try(socket.connect("localhost", 80))
socket.udp()
unconnected
A unconnected UDP object.
unconnected:close()
Note: It is important to close all used sockets once they are not needed, since , in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
unconnected:getsockname()
unconnected:receive(size)
size
:
optional Specifies the maximum size of the datagram to be
retrieved. If there are more than size bytes available in the datagram, the
excess bytes are discarded. If there are less then size bytes available in the
current datagram, the available bytes are returned. If size is omitted,
the maximum datagram size is used (which is currently limited by the
implementation to 8192 bytes).
unconnected:receivefrom(size)
size
:
address, port
unconnected:sendto(datagram, ip, port)
datagram
:
A _#string" with the datagram contents. The maximum datagram
size for UDP is 64K minus IP layer overhead. However datagrams larger than the
link layer packet size will be fragmented, which may deteriorate performance
and/or reliability.
ip
:
The IP address of the recipient. Host names are not allowed for
performance reasons.
port
:
The port number at the recipient.
unconnected.setoption(option, value)
Note: The descriptions above come from the man pages.
option
:
The option name:
value
:
Depends on the option being set.
unconnected:setpeername(address, port)
address
:
port
:
unconnected:setsockname(address, port)
address
:
Can be an IP address or a host name. If address is '*' the
system binds to all local interfaces using the constant INADDR_ANY.
port
:
If port is 0, the system chooses an ephemeral port.
#nil, #string: In error cases, error string is provided.
unconnected:settimeout(value)
Note: In UDP, the #connected.send and #unconnected.sendto methods never block (the datagram is just passed to the OS and the call returns immediately). Therefore, the settimeout method has no effect on them.
Note: The old timeout method is deprecated. The name has been changed for sake of uniformity, since all other method names already contained verbs making their imperative nature obvious.
value
:
The amount of time to wait, in seconds. The #nil timeout
value allows operations to block indefinitely. Negative timeout values have
the same effect.