lights FAQ Forum   github.com/Starkkz/bnet
bnet

Networking
socket
bnet
socketloop
libcurl
libssh2

bnet

networking library


local socket = require'bnet'

Networking library, API compatible with LuaSocket 2.0.2.

This library ports most of the functions from LuaSocket 2.0.2 in pure Lua code, you won't need to install any other dynamic libraries.

Why is it called bnet? Because it's first version was intended to be a port from the BNet library for BlitzMax in Lua, but later it was improved to be API compatible with the traditional LuaSocket library.

API

DNS (in socket)
socket.dns.gethostname() Returns the standard host name for the machine as a string.
socket.dns.tohostname(address) Converts from IP address to host name. Address can be an IP address or host name. The function returns a string with the canonic host name of the given address, followed by a table with all information returned by the resolver. In case of error, the function returns nil followed by an error message.
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._BNETVERSION This constant has a string describing the current library version.
socket.protect(func) Converts a function that throws exceptions into a safe function. This function only catches exceptions thrown by the try and newtry functions. It does not catch normal Lua errors. Func is a function that calls 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.
socket.select(recvt, sendt [, timeout]) Waits for a number of sockets to change status. 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 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.
socket.skip(d [, ret1, ret2 ... retN]) 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.
socket.sleep(time) Freezes the program execution during a given amount of time. Time is the number of seconds to sleep for.
socket.gettime() Returns the time in seconds, relative to the origin of the universe. You should subtract the values returned by this function to get meaningful values.
TCP (in socket)
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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
tcp: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.
UDP (in socket)
socket.udp() Creates and returns an unconnected UDP object. In case of success, a new unconnected UDP object returned. In case of error, nil is returned, followed by an error message.
udp:close() Closes a UDP 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.
udp:getpeername() Retrieves information about the peer associated with a connected UDP object. Returns the IP address and port number of the peer.
Note: It makes no sense to call this method on unconnected objects.
udp: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.
Note: UDP sockets are not bound to any address until the setsockname or the sendto method is called for the first time (in which case it is bound to an ephemeral port and the wild-card address).
udp:receive([size]) Receives a datagram from the UDP object. If the UDP object is connected, only datagrams coming from the peer are accepted. Otherwise, the returned datagram can come from any host. The optional size parameter 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). In case of success, the method returns the received datagram. In case of timeout, the method returns nil followed by the string 'timeout'.
udp:receivefrom([size]) Works exactly as the receive method, except it returns the IP address and port as extra return values.
udp:send(datagram) Sends a datagram to the UDP peer of a connected object. Datagram is 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. If successful, the method returns 1. In case of error, the method returns nil followed by an error message.
Note: In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).
udp:sendto(datagram, ip, port) Sends a datagram to the specified IP address and port number. Datagram is 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 is the IP address of the recipient. Host names are not allowed for performance reasons. Port is the port number at the recipient. If successful, the method returns 1. In case of error, the method returns nil followed by an error message.
Note: In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).
udp:setpeername('*') Changes the peer of a UDP object. This method turns an unconnected UDP object into a connected UDP object or vice versa. For connected objects, outgoing datagrams will be sent to the specified peer, and datagrams received from other peers will be discarded by the OS. Connected UDP objects must use the send and receive methods instead of sendto and receivefrom. Address can be an IP address or a host name. Port is the port number. 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. In case of error the method returns nil followed by an error message. In case of success, the method returns 1.
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.
udp:setsockname(address, port) Binds the UDP object to a local address. 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. If port is 0, the system chooses an ephemeral port. If successful, the method returns 1. In case of error, the method returns nil followed by an error message.
Note: This method can only be called before any datagram is sent through the UDP object, and only once. Otherwise, the system automatically binds the object to all local interfaces and chooses an ephemeral port as soon as the first datagram is sent. After the local address is set, either automatically by the system or explicitly by setsockname, it cannot be changed.
udp:settimeout(value) Changes the timeout values for the object. By default, the receive and receivefrom operations are blocking. That is, any call to the methods will block indefinitely, until data arrives. The settimeout function defines a limit on the amount of time the functions 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. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
Note: In UDP, the send and 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.

Last updated: 2 years ago | Edit on GitHub

Pkg type:Lua+ffi
Version: f9a5797
Last commit:
License: MIT
Import ver: 0.0.3
Requires: luajit 
Required by: none

Top