Skip to content

class Socket

https://lunarmodules.github.io/luasocket/socket.html

The socket namespace

The socket namespace contains the core functionality of LuaSocket.

To obtain the socket namespace, run:

-- loads the socket module
local socket = require("socket")

😱 Types incomplete or incorrect? 🙏 Please contribute!


methods


Socket.gettime


function Socket.gettime() -> time number

@return time - for example 1683526723.1653

😱 Types incomplete or incorrect? 🙏 Please contribute!

Return the UNIX time in seconds.

You should subtract the values returned by this function to get meaningful values.

Example:

t = socket.gettime()
-- do stuff
print(socket.gettime() - t .. " seconds elapsed")

Reference:

Socket.newtry


function Socket.newtry(finalizer: function) ->  function
@param finalizer - -Finalizer is a function that will be called before try throws the exception.

@return - The function returns your customized try function.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Creates and returns a clean try function that allows for cleanup before the exception is raised.

Note: This idea saved a lotof 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)

Socket.protect


function Socket.protect(func: function) ->  function
@param func - func is a function that calls try (or assert, or error) to throw exceptions.

@return - Returns an equivalent function that instead of throwing exceptions in case of a failed trycall, returns nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Converts a function that throws exceptions into a safe function. This function only catches exceptions thrown by the try and newtryfunctions. It does not catch normal Lua errors.

Socket.select


function Socket.select(
  recvt: table?,
  sendt: table?,
  timeout: integer?
)
@param recvt - recvt is an array with the sockets to test for characters available for reading.

@param sendt - Sockets in the sendt array are watched to see if it is OK to immediately write on them.

@param timeout - 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.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Waits for a number of sockets to change status.

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, "select failed" if the call to select failed, 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.

Note:select can monitor a limited number of sockets, as defined by the constant socket._SETSIZE. This number may be as high as 1024 or as low as 64 by default, depending on the system. It is usually possible to change this at compile time. Invoking select with a larger number of sockets will raise an error.

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 notready for sending.

Another important note: calling select with a server socket in the receive parameter before a call to accept does notguarantee acceptwill 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.

Using select with non-socket objects: Any object that implements getfd and dirty can be used with select, allowing objects from other libraries to be used within a socket.select driven loop.

Socket.sink


function Socket.sink(
  mode: ("http-chunked"|"close-when-done"|"keep-open"),
  socket: any
)

Creates an LTN12 sink from a stream socket object.

Mode defines the behavior of the sink. The following options are available:

  • "http-chunked": sends data through socket after applying the chunked transfer coding, closing the socket when done;
  • "close-when-done": sends all received data through the socket, closing the socket when done;
  • "keep-open": sends all received data through the socket, leaving it open when done.

Socket is the stream socket object used to send the data.

The function returns a sink with the appropriate behavior.

Socket.skip


function Socket.skip(
  d: integer,
  ...: any
)

Drops a number of arguments and returns the remaining.

D is the number of arguments to drop. Ret1 to retN are the arguments.

The function returns retd+1 to retN.

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)(.?)"))

Socket.sleep


function Socket.sleep(time: integer)
@param time - time is the number of seconds to sleep for. If time is negative, the function returns immediately.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Freeze the program execution during a given amount of time.

Reference:

Socket.source


function Socket.source(
  mode: ("http-chunked"|"by-length"|"until-closed"),
  socket: any,
  timeout: integer
)

Creates an LTN12 source from a stream socket object.

Mode defines the behavior of the source. The following options are available:

  • "http-chunked": receives data from socket and removes the chunked transfer codingbefore returning the data;
  • "by-length": receives a fixed number of bytes from the socket. This mode requires the extra argument length;
  • "until-closed": receives data from a socket until the other side closes the connection.

Socket is the stream socket object used to receive the data.

The function returns a source with the appropriate behavior.

Socket.try


function Socket.try(...: any)

Throws an exception in case ret1 is falsy, using ret2 as the error message. The exception is supposed to be caught by a protected function only.

Ret1 to retN can be arbitrary arguments, but are usually the return values of a function call nested with try.

The function returns ret1 to retN if ret1 is not nil or false. Otherwise, it calls error passing ret2 wrapped in a table with metatable used by protectto distinguish exceptions from runtime errors.

-- connects or throws an exception with the appropriate error message
c = socket.try(socket.connect("localhost", 80))

Socket.bind


function Socket.bind(
  address: string,
  port: integer,
  backlog: integer?
) ->  TCPSocketServer {
    accept = function,
    getoption = function,
    setoption = function,
}
@param backlog - Defaults to 32.

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. Optionally, user can also specify the backlog argument to the listen method.

Note: The server object returned will have the option reuseaddr set to true.

Socket.connect


function Socket.connect(
  address: string,
  port: integer,
  locaddr: string?,
  locport: integer?,
  family: ("inet"|"inet6")?
)
 ->  TCPSocketClient?
 ->  string?
@param locaddr - The local address

@param locport - The local port

@param family - If not specified, the family depends on your system configuration.

@return - Returns the client on success, or nil and an error message on failure.

😱 Types incomplete or incorrect? 🙏 Please contribute!

@return - Returns the client on success, or nil and an error message on failure.

😱 Types incomplete or incorrect? 🙏 Please contribute!

This function is a shortcut that creates and returns a TCP client object connected to a remote address at a given port. Optionally, the user can also specify the local address and port to bind (locaddr and locport), or restrict the socket family to "inet" or "inet6".

Two variations of connect are defined as simple helper functions that restrict the family, socket.connect4 and socket.connect6.

Socket.connect4


function Socket.connect4(
  address: string,
  port: integer,
  locaddr: string?,
  locport: integer?
)
 ->  TCPSocketClient?
 ->  string?
@param locaddr - The local address

@param locport - The local port

@return - Returns the client on success, or nil and an error message on failure.

😱 Types incomplete or incorrect? 🙏 Please contribute!

@return - Returns the client on success, or nil and an error message on failure.

😱 Types incomplete or incorrect? 🙏 Please contribute!

This function is a shortcut that creates and returns an IPv4 TCP client object connected to a remote address at a given port. Optionally, the user can also specify the local address and port to bind (locaddr and locport)

Socket.connect6


function Socket.connect6(
  address: string,
  port: integer,
  locaddr: string?,
  locport: integer?
)
 ->  TCPSocketClient?
 ->  string?
@param locaddr - The local address

@param locport - The local port

@return - Returns the client on success, or nil and an error message on failure.

😱 Types incomplete or incorrect? 🙏 Please contribute!

@return - Returns the client on success, or nil and an error message on failure.

😱 Types incomplete or incorrect? 🙏 Please contribute!

This function is a shortcut that creates and returns an IPv6 TCP client object connected to a remote address at a given port. Optionally, the user can also specify the local address and port to bind (locaddr and locport)

Socket.tcp


function Socket.tcp()
 ->  TCPSocketMaster?
 ->  string?

@return - New master object if successful, otherwise nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

@return - New master object if successful, otherwise nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Creates and returns an TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method.

Note: The choice between IPv4 and IPv6 happens during a call to bind or connect, depending on the address family obtained from the resolver.

Note: Before the choice between IPv4 and IPv6 happens, the internal socket object is invalid and therefore setoption will fail.

Socket.tcp4


function Socket.tcp4()
 ->  TCPSocketMaster?
 ->  string?

@return - New master object if successful, otherwise nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

@return - New master object if successful, otherwise nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Creates and returns an IPv4 TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method.

Socket.tcp6


function Socket.tcp6()
 ->  TCPSocketMaster?
 ->  string?

@return - New master object if successful, otherwise nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

@return - New master object if successful, otherwise nil followed by an error message.

😱 Types incomplete or incorrect? 🙏 Please contribute!

Creates and returns an IPv6 TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method.

Note: The TCP object returned will have the option "ipv6-v6only" set to true.

Socket.udp


function Socket.udp()
 ->  (UDPSocketConnected|UDPSocketUnconnected)?
 ->  SocketReturnError

Creates and returns an unconnected UDP object. Unconnected objects support the sendto, receive, receivefrom, getoption, getsockname, setoption, settimeout, setpeername, setsockname, and close. The setpeername is used to connect the object.

In case of success, a new unconnected UDP object returned. In case of error, nil is returned, followed by an error message.

Note: The choice between IPv4 and IPv6 happens during a call to sendto, setpeername, or sockname, depending on the address family obtained from the resolver.

Note: Before the choice between IPv4 and IPv6 happens, the internal socket object is invalid and therefore setoption will fail.

To mark a socket as connected or unconnected use ---@cast. Example:

local server, err = socket.udp()
local client, err = socket.udp()
---@cast server UDPSocketUnconnected
server:setsockname("127.0.0.1", 12345)
---@cast client UDPSocketConnected
client:setpeername("127.0.0.1", 12345)

Socket.udp4


function Socket.udp4()
 ->  (UDPSocketConnected|UDPSocketUnconnected)?
 ->  SocketReturnError

Creates and returns an unconnected IPv4 UDP object. Unconnected objects support the sendto, receive, receivefrom, getoption, getsockname, setoption, settimeout, setpeername, setsockname, and close. The setpeername is used to connect the object.

In case of success, a new unconnected UDP object returned. In case of error, nil is returned, followed by an error message.

To mark a socket as connected or unconnected use ---@cast. Example:

local server, err = socket.udp4()
local client, err = socket.udp4()
---@cast server UDPSocketUnconnected
server:setsockname("127.0.0.1", 12345)
---@cast client UDPSocketConnected
client:setpeername("127.0.0.1", 12345)

Socket.udp6


function Socket.udp6()
 ->  (UDPSocketConnected|UDPSocketUnconnected)?
 ->  SocketReturnError

Creates and returns an unconnected IPv6 UDP object. Unconnected objects support the sendto,

In case of success, a new unconnected UDP object returned. In case of error, nil is returned, followed by an error message.

Note: The UDP object returned will have the option "ipv6-v6only" set to true.

To mark a socket as connected or unconnected use ---@cast. Example:

local server, err = socket.udp6()
local client, err = socket.udp6()
---@cast server UDPSocketUnconnected
server:setsockname("127.0.0.1", 12345)
---@cast client UDPSocketConnected
client:setpeername("127.0.0.1", 12345)

fields


Socket.headers


Socket.headers: table

😱 Types incomplete or incorrect? 🙏 Please contribute!

Socket._DEBUG


Socket._DEBUG : boolean

This constant is set to true if the library was compiled with debug support.

Socket._DATAGRAMSIZE


Socket._DATAGRAMSIZE : integer

Default datagram size used by calls to receiveand receivefrom. (Unless changed in compile time, the value is 8192.)

Socket._SETSIZE


Socket._SETSIZE : integer

The maximum number of sockets that the select function can handle.

Socket._SOCKETINVALID


Socket._SOCKETINVALID : any

The OS value for an invalid socket. This can be used with tcp:getfdand tcp:setfdmethods.

Socket._VERSION


Socket._VERSION : string

This constant has a string describing the current LuaSocket version.