## TCP

socket.tcp()

Creates and returns a 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.

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

server:accept()

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

If a connection is successfully initiated, a client object is returned. If a timeout condition is met, the method returns `nil` followed by the error string '`timeout`'. Other errors are reported by `nil` followed by a message describing the error.

Note: calling `socket.select` with a server object in the `recvt` parameter before a call to `accept` does not guarantee `accept` will return immediately. Use the `settimeout` method or `accept` might block until another client shows up.

master:bind(address, port)

Binds a master object to `address` and `port` on the local host.

`Address` can be an IP address or a host name. `Port` must be an integer number in the range [0..64K). If `address` is '`*`', the system binds to all local interfaces using the `INADDR_ANY` constant. If `port` is 0, the system automatically chooses an ephemeral port.

In case of success, the method returns 1. In case of error, the method returns `nil` followed by an error message.

Note: The function `socket.bind` is available and is a shortcut for the creation of server sockets.

master:close()
client:close()
server:close()

Closes a TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the `close` method) are allowed on a closed socket.

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.

master:connect(address, port)

Attempts to connect a master object to a remote host, transforming it into a client object. Client objects support methods `send`, `receive`, `getsockname`, `getpeername`, `settimeout`, and `close`.

`Address` can be an IP address or a host name. `Port` must be an integer number in the range [1..64K).

In case of error, the method returns `nil` followed by a string describing the error. In case of success, the method returns 1.

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.

client:getpeername()

Returns information about the remote side of a connected client object.

Returns a string with the IP address of the peer, followed by the port number that peer is using for the connection. In case of error, the method returns `nil`.

Note: It makes no sense to call this method on server objects.

master:getsockname()
client:getsockname()
server:getsockname()

Returns the local address information associated to the object.

The method returns a string with local IP address and a number with the port. In case of error, the method returns `nil`.

master:getstats()
client:getstats()
server:getstats()

Returns accounting information on the socket, useful for throttling of bandwidth.

The method returns the number of bytes received, the number of bytes sent, and the age of the socket object in seconds.

master:listen(backlog)

Specifies the socket is willing to receive connections, transforming the object into a server object. Server objects support the `accept`, `getsockname`, `setoption`, `settimeout`, and `close` methods.

The parameter `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.

In case of success, the method returns 1. In case of error, the method returns `nil` followed by an error message.

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

Reads data from a client object, according to the specified read pattern. Patterns follow the Lua file I/O format, and the difference in performance between all patterns is negligible.

`Pattern` can be any of the following:

- '`*a`': reads from the socket until the connection is closed. No end-of-line translation is performed;
- '`*l`': reads a line of text from the socket. The line is terminated by a LF character (ASCII 10), optionally preceded by a CR character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern. This is the default pattern;
- `number`: causes the method to read a specified `number` of bytes from the socket.

`Prefix` is an optional string to be concatenated to the beginning of any received data before return.

If successful, the method returns the received pattern. In case of error, the method returns `nil` followed by an error message which can be the string '`closed`' in case the connection was closed before the transmission was completed or the string '`timeout`' in case there was a timeout during the operation. Also, after the error message, the function returns the partial result of the transmission.

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.

client:send(data [, i [, j]])

Sends `data` through client object.

`Data` is the string to be sent. The optional arguments `i` and `j` work exactly like the standard `string.sub` 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. Notice that, if `i` is 1 or absent, this is effectively the total number of bytes sent. 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 '`closed`' in case the connection was closed before the transmission was completed or the string '`timeout`' in case there was a timeout during the operation.

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.

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

Sets options for the TCP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.

`Option` is a string with the option name, and `value` depends on the option being set:

- '`keepalive`': Setting this option to `true` enables the periodic transmission of messages on a connected socket. Should the connected party fail to respond to these messages, the connection is considered broken and processes using the socket are notified;
- '`linger`': Controls the action taken when unsent data are queued on a socket and a close is performed. The value is a table with a boolean entry '`on`' and a numeric entry for the time interval '`timeout`' in seconds. If the '`on`' field is set to `true`, the system will block the process on the close attempt until it is able to transmit the data or until '`timeout`' has passed. If '`on`' is `false` and a close is issued, the system will process the close in a manner that allows the process to continue as quickly as possible. I do not advise you to set this to anything other than zero;
- '`reuseaddr`': Setting this option indicates that the rules used in validating addresses supplied in a call to `bind` should allow reuse of local addresses;
- '`tcp-nodelay`': Setting this option to `true` disables the Nagle's algorithm for the connection.

The method returns 1 in case of success, or `nil` otherwise.

Note: The descriptions above come from the man pages.

master:setstats(received, sent, age)
client:setstats(received, sent, age)
server:setstats(received, sent, age)

Resets accounting information on the socket, useful for throttling of bandwidth.

`Received` is a number with the new number of bytes received. `Sent` is a number with the new number of bytes sent. `Age` is the new age in seconds.

The method returns 1 in case of success and `nil` otherwise.

master:settimeout(value [, mode])
client:settimeout(value [, mode])
server:settimeout(value [, mode])

Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods `send`, `receive`, and `accept` will block indefinitely, until the operation completes. The `settimeout` method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code.

The amount of time to wait is specified as the `value` parameter, in seconds. There are two timeout modes and both can be used together for fine tuning:

- '`b`': block timeout. Specifies the upper limit on the amount of time LuaSocket can be blocked by the operating system while waiting for completion of any single I/O operation. This is the default mode;
- '`t`': total timeout. Specifies the upper limit on the amount of time LuaSocket can block a Lua script before returning from a call.

The `nil` timeout `value` allows operations to block indefinitely. Negative timeout values have the same effect.

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.

client:shutdown(mode)

Shuts down part of a full-duplex connection.

Mode tells which way of the connection should be shut down and can take the value:

- "`both`": disallow further sends and receives on the object. This is the default mode;
- "`send`": disallow further sends on the object;
- "`receive`": disallow further receives on the object.

This function returns 1.