Reference
NOTE: Some functions require DNS lookups, which is handled internally
by LuaSocket. This is being done in a blocking manner. Hence every function
that accepts a hostname as an argument (e.g. tcp:connect()
,
udp:sendto()
, etc.) is potentially blocking on the DNS resolving part.
So either provide IP addresses (assuming the underlying OS will detect those and resolve
locally, non-blocking) or accept that the lookup might block.
Getting started examples
Example for a server handling incoming connections:
local copas = require("copas") local socket = require("socket") local address = "*" local port = 20000 local ssl_params = { wrap = { mode = "server", protocol = "any", -- not really secure... }, } local server_socket = assert(socket.bind(address, port)) local function connection_handler(skt) local data, err = skt:receive() -- do something end copas.addserver(server_socket, copas.handler(connection_handler, ssl_params)) copas.loop()
Example for a client making a connection to a remote server:
local copas = require("copas") local socket = require("socket") copas.addthread(function() local port = 20000 local host = "somehost.com" local ssl_params = { wrap = { mode = "client", protocol = "any", -- not really secure... }, } local sock = copas.wrap(socket.tcp(), ssl_params) assert(sock:connect(host, port)) local data, err = sock:receive("*l") -- do something end) copas.loop()
Copas dispatcher main functions
The group of functions is relative to the use of the dispatcher itself and are used to register servers and to execute the main loop of Copas:
copas.addserver(server, handler[, timeout])
- Adds a new
server
and itshandler
to the dispatcher using an optionaltimeout
.
server
is a LuaSocket server socket created usingsocket.bind()
.
handler
is a function that receives a LuaSocket client socket and handles the communication with that client.
timeout
is the timeout in seconds. Upon accepting connections, the timeout will be inherited by TCP client sockets (only applies to TCP).
The handler will be executed in parallel with other threads and the registered handlers as long as it uses the Copas socket functions. coro = copas.addthread(func [, ...])
- Adds a function as a new coroutine/thread to the dispatcher. The optional
parameters will be passed to the function
func
.
The thread will be executed in parallel with other threads and the registered handlers as long as it uses the Copas socket/sleep functions. It returns the created coroutine. copas.autoclose
- Constant that controls whether sockets are automatically closed.
When a TCP handler function completes and terminates, then the client socket will be automatically closed whencopas.autoclose
is truthy. copas.finished()
- Checks whether anything remains to be done.
Returnsfalse
when the socket lists for reading and writing are empty and there is not another (sleeping) task to execute. NOTE: when tasks or sockets have been scheduled/setup this function will returntrue
even if the loop has not yet started. See alsocopas.running
. func = copas.handler(connhandler [, sslparams])
- Wraps the
connhandler
function. Returns a new function that wraps the client socket, and (ifsslparams
is provided) performs the ssl handshake, before callingconnhandler
.
Seesslparams
definition below. copas.loop([init_func, ][timeout])
- Starts the Copas loop accepting client connections for the
registered servers and handling those connections with the corresponding
handlers. Every time a server accepts a connection, Copas calls the
associated handler passing the client socket returned by
socket.accept()
. Theinit_func
function is an optional initialization function that runs as a Copas thread. Thetimeout
parameter is optional, and is passed to thecopas.step()
function. The loop returns whencopas.finished() == true
. copas.removeserver(skt [, keep_open])
- Removes a server socket from the Copas scheduler.
By default, the socket will be closed to allow the socket to be reused right away after
removing the server. If
keep_open
istrue
, the socket is removed from the scheduler but it is not closed. copas.removethread(coroutine)
- Removes a coroutine added to the Copas scheduler.
Takes a
coroutine
created bycopas.addthread()
and removes it from the dispatcher the next time it tries to resume. Ifcoroutine
isn't registered, it does nothing. copas.running
- A flag set to
true
whencopas.loop()
starts, and reset tofalse
when the loop exits. See alsocopas.finished()
. copas.setErrorHandler(func, [default])
- Sets the error handling function for the current thread. If
default
is truthy, then the handler will become the new default, used for all threads that do not have their own set. Any errors will be forwarded to this handler, which will receive the error, coroutine, and socket as arguments. See the Copas source code on how to deal with the arguments when implementing your own. copas.wrap(skt [, sslparams] )
- Wraps a LuaSocket socket and returns a Copas socket that implements LuaSocket's API
but use Copas' methods like
copas.send()
andcopas.receive()
automatically. If thesslparams
is provided, then a call to the wrappedskt:connect()
method will automatically include the handshake (and in that caseconnect()
might throw an error instead of returning nil+error, seecopas.dohandshake()
).
Seesslparams
definition below. sslparams
- This is the data-structure that is passed to the
copas.handler
, andcopas.wrap
functions. Passing the structure will allow Copas to take care of the entire TLS handshake process. The structure is set up to mimic the LuaSec functions for the handshake.{ wrap = table | context, -- parameter to LuaSec 'wrap()' sni = { -- parameters to LuaSec 'sni()' names = string | table -- 1st parameter strict = bool -- 2nd parameter } }
Non-blocking data exchange and timer/sleep functions
These are used by the handler functions to exchange data with
the clients, and by threads registered with addthread
to
exchange data with other services.
copas.sleep([sleeptime])
- Pauses the current co-routine. Parameter
sleeptime
(in seconds) is optional and defaults to 0. Ifsleeptime < 0
then it will sleep until explicitly woken by a call tocopas.wakeup()
. copas.wakeup(co)
co
is the coroutine to wakeup, seecopas.sleep()
.sock:close(...)
- Equivalent to the LuaSocket method (after
copas.wrap
). sock:connect(...)
- Non-blocking equivalent to the LuaSocket method (after
copas.wrap
).
Ifsslparams
was provided when wrapping the socket, theconnect
method will also perform the full TLS handshake. So afterconnect
returns the connection will be secured. sock:dohandshake(...)
- Non-blocking quivalent to the LuaSocket method (after
copas.wrap
). Instead of using this method, it is preferred to pass thesslparams
to the functionscopas.handler
(for incoming connections) andcopas.wrap
(for outgoing connections), which then ensures that the connection will automatically be secured when started. sock:receive(...)
- Non-blocking equivalent to the LuaSocket method (after
copas.wrap
). sock:send(...)
- Non-blocking equivalent to the LuaSocket method (after
copas.wrap
). sock:settimeout(...)
- Equivalent to the LuaSocket method (after
copas.wrap
). sock:sni(...)
- Equivalent to the LuaSec method (after
copas.wrap
). Instead of using this method, it is preferred to pass thesslparams
to the functionscopas.handler
(for incoming connections) andcopas.wrap
(for outgoing connections), which then ensures that the connection will automatically be secured when started. lock:destroy()
- Will destroy the lock and release all waiting threads. The result for those
threads will be
nil + "destroyed" + wait_time
. lock:get([timeout])
- Will try and acquire the lock. The optional
timeout
can be used to override the timeout value set when the lock was created. If the the lock is not available, the coroutine will yield until either the lock becomes available, or it times out. The one exception is whentimeout
is 0, then it will immediately return without yielding. Upon success, it will return thewait-time
in seconds. Upon failure it will returnnil + error + wait-time
. Upon a timeout the error value will be "timeout". lock.new([timeout], [not_reentrant])
- Creates and returns a new lock. The
timeout
specifies the default timeout for the lock in seconds, and defaults to 10. By default the lock is re-entrant, except ifnot_reentrant
is set to a truthy value. lock:release()
- Releases the currently held lock. Returns
true
ornil + error
. semaphore:get_count()
- Returns the number of resources currently available in the semaphore.
semaphore:get_wait()
- Returns the total number of resources requested by all currently waiting threads minus
the available resources. Such that
sempahore:give(semaphore:get_wait())
will release all waiting threads and leave the semaphore with 0 resources. If there are no waiting threads then the result will be 0, and the number of resources in the semaphore will be greater than or equal to 0. semaphore:give([given])
- Gives resources to the semaphore. Parameter
given
is the number of resources given to the semaphore, if omitted it defaults to 1. If the total resources in the semaphore exceed the maximum, then it will be capped at the maximum. In that case the result will benil + "too many"
. semaphore.new(max, [start], [timeout])
- Creates and returns a new semaphore (fifo).
max
specifies the maximum number of resources the semaphore can hold. The optionalstart
parameter (default 0) specifies the number of resources upon creation. Thetimeout
specifies the default timeout for the lock in seconds, and defaults to 10. semaphore:take([requested], [timeout])
- Takes resources from the semaphore. Parameter
requested
is the number of resources requested from the semaphore, if omitted it defaults to 1. If not enough resources are available it will yield and wait until enough resources are available, or a timeout occurs. The exception is whentimeout
is set to 0, in that case it will immediately return without yielding if there are not enough resources available. The optionaltimeout
parameter can be used to override the default timeout as set upon semaphore creation. Returnstrue
upon success ornil + "timeout"
on a timeout. In case more resources are requested than maximum available the error will be"too many"
. timer.new(options)
- Creates and returns an (armed) timer object. The
options
table has the following fields;options.recurring
booleanoptions.delay
expiry delay in secondsoptions.initial_delay
(optional) seetimer:arm()
options.params
(optional) an opaque value that is passed to the callback upon expiryoptions.callback
is the function to execute on timer expiry. The callback function hasfunction(timer_obj, params)
as signature, whereparams
is the value initially passed inoptions.params
timer:arm([initial_delay])
- Arms a timer that was previously cancelled or exited. Returns the timer.
The optional parameter
initial_delay
, determines the first delay. For example a recurring timer withdelay = 5
, andinitial_delay = 0
will execute immediately and then recur every 5 seconds. timer:cancel()
- Will cancel the timer.
High level request functions
The last ones are the higher level client functions to perform requests to (remote) servers.
copas.http.request(url [, body])
orcopas.http.request(requestparams)
- Performs an http or https request, identical to the LuaSocket and LuaSec
implementations, but wrapped in an async operation. As opposed to the original
implementations, this one also allows for redirects cross scheme (http to https and
viceversa).
Note: https to http redirects are not allowed by
default, but only when
requestparams.redirect == "all"
copas.ftp.put(url, content)
orcopas.ftp.put(requestparams)
- Performs an ftp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.ftp.get(url)
orcopas.ftp.get(requestparams)
- Performs an ftp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.smtp.send(msgparams)
- Sends an smtp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.smtp.message(msgt)
- Just points to
socket.smtp.message
, provided so thecopas.smtp
module is a drop-in replacement for thesocket.smtp
module copas.limit.new(max)
- Creates and returns a `limitset` that limits the concurrent tasks to
max
number of running tasks. Eg. 100 http requests, in a set withmax == 10
, then no more than 10 requests will be performed simultaneously. Only when a request finishes, the next will be started. limitset:addthread(func [, ...])
- Identical to
copas.addthread
, except that it operates within the limits of the set of running tasks. limitset:wait()
- Will yield until all tasks in the set have finished.
Low level Copas functions
Most of these are wrapped in the socket wrapper functions, and wouldn't need to be used by user code on a regular basis.
copas.close(skt)
- Closes the socket. Any read/write operations in progress will return with an error.
copas.connect(skt, address, port)
- Connects and transforms a master socket to a client just like LuaSocket
socket:connect()
. The Copas version does not block and allows the multitasking of the other handlers and threads. copas.dohandshake(skt, sslparams)
- Performs an ssl handshake on an already connected TCP client socket. It returns the new ssl-socket on success, or throws an error on failure.
copas.flush(skt)
- (deprecated)
copas.receive(skt [, pattern])
(TCP) orcopas.receive(size)
(UDP)- Reads data from a client socket according to a pattern just like LuaSocket
socket:receive()
. The Copas version does not block and allows the multitasking of the other handlers and threads. Note: for UDP sockets thesize
parameter is NOT optional. For the wrapped functionsocket:receive([size])
it is optional again. copas.receivefrom(skt [, size])
- Reads data from a UDP socket just like LuaSocket
socket:receivefrom()
. The Copas version does not block and allows the multitasking of the other handlers and threads. copas.send(skt, data [, i [, j]])
(TCP) orcopas.send(skt, datagram)
(UDP)- Sends data to a client socket just like
socket:send()
. The Copas version is buffered and does not block, allowing the multitasking of the other handlers and threads. Note: only for TCP, UDP send doesn't block, hence doesn't require this function to be used. copas.sendto(skt, datagram, ip, port)
- (deprecated, since UDP sending doesn't block)
copas.settimeout(skt, [timeout])
- Sets the timeout (in seconds) for a socket. The default is to not have a timeout and wait
indefinitely. If a timeout is hit, the operation will return
nil + "timeout"
. Timeouts are applied on:receive, receivefrom, receivePartial, send, connect, dohandshake
. Seecopas.useSocketTimeoutErrors()
below for alternative error messages. bool = copas.step([timeout])
- Executes one copas iteration accepting client connections for the
registered servers and handling those connections with the corresponding
handlers. When a server accepts a connection, Copas calls the
associated handler passing the client socket returned by
socket.accept()
. Thetimeout
parameter is optional. It returnsfalse
when no data was handled (timeout) ortrue
if there was data handled (or alternatively nil + error message in case of errors). NOTE: thecopas.running
flag will not automatically be (un)set. So when using your own main loop, consider manually setting the flag. copas.timeout(delay, callback)
- Creates a timeout timer for the current coroutine. The
delay
is the timeout in seconds, and thecallback
will be called upon an actual timeout occuring. Calling it withdelay = 0
will cancel the timeout. Calling it repeatedly will simply replace the timeout on the current coroutine and any previous callback set will no longer be called. NOTE: The timeouts are a low-level Copas feature, and should only be used to wrap an explicit yield to the Copas scheduler. They should not be used to wrap user code. For usage examples see thelock
andsemaphore
implementations. copas.useSocketTimeoutErrors([bool])
- Sets the timeout errors to return for the current co-routine.
The default is
false
, meaning that a timeout error will always return an error string"timeout"
. If you are porting an existing application to Copas and want LuaSocket or LuaSec compatible error messages then set it totrue
. In case of using socket timeout errors, they can also be"wantread"
or"wantwrite"
when using ssl/tls connections. These can be returned at any point if during a read or write operation an ssl-renegotiation happens. Due to platform difference theconnect
method may also return"Operation already in progress"
as a timeout error message.