Copas
Coroutine Oriented Portable Asynchronous Services for Lua

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.

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 its handler to the dispatcher using an optional timeout.
server is a LuaSocket server socket created using socket.bind().
handler is a function that receives a LuaSocket client socket and handles the communication with that client.
timeout is the timeout for blocking I/O in seconds. The handler will be executed in parallel with other threads and the registered handlers as long as it uses the Copas socket functions.
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 when copas.autoclose is truthy (neither nil nor false).
copas.finished()
Checks whether anything remains to be done.
Returns false 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 return true even if the loop has not yet started. See also copas.running.
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(). The init_func function is an optional initialization function that runs as a Copas thread. The timeout parameter is optional, and is passed to the copas.step() function. The loop returns when copas.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 is true, 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 by copas.addthread() and removes it from the dispatcher the next time it tries to resume. If coroutine isn't registered, it does nothing.
copas.running
A flag set to true when copas.loop() starts, and reset to false when the loop exits. See also copas.finished().
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(). The timeout parameter is optional. It returns false when no data was handled (timeout) or true if there was data handled (or alternatively nil + error message in case of errors).
NOTE: the copas.running flag will not automatically be (un)set. So when using your own main loop, consider manually setting the flag.
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.timeout(delay, callback)
Creates a timeout timer for the current coroutine. The delay is the timeout in seconds, and the callback will be called upon an actual timeout occuring.
Calling it with delay = 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 setting socket timeouts see copas.settimeout() below.

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.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.handler(connhandler [, sslparams])
Wraps the connhandler function. Returns a new function that wraps the client socket, and (if sslparams is provided) performs the ssl handshake, before calling connhandler.
copas.receive(skt [, pattern]) (TCP) or
copas.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 the size parameter is NOT optional. For the wrapped function socket: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) or
copas.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.
See copas.useSocketTimeoutErrors() below for alternative error messages.
copas.sleep([sleeptime])
Pauses the current co-routine. Parameter sleeptime (in seconds) is optional and defaults to 0. If sleeptime < 0 then it will sleep until explicitly woken by a call to copas.wakeup().
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 to true.

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 the connect method may also return "Operation already in progress" as a timeout error message.
copas.wakeup(co)
co is the coroutine to wakeup.
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() and copas.receive() automatically. If the sslparams is provided, then a call to the wrapped skt:connect() method will automatically include the handshake (and in that case connect() might throw an error instead of returning nil+error, see copas.dohandshake()). To use ssl with defaults; provide an empty table.
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 when timeout is 0, then it will immediately return without yielding.
Upon success, it will return the wait-time in seconds. Upon failure it will return nil + 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 if not_reentrant is set to a truthy value.
lock:release()
Releases the currently held lock. Returns true or nil + 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 be nil + "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 optional start parameter (default 0) specifies the number of resources upon creation. The timeout 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 when timeout is set to 0, in that case it will immediately return without yielding if there are not enough resources available.
The optional timeout parameter can be used to override the default timeout as set upon semaphore creation. Returns true upon success or nil + "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 boolean
  • options.delay expiry delay in seconds
  • options.initial_delay (optional) see timer:arm()
  • options.params (optional) an opaque value that is passed to the callback upon expiry
  • options.callback is the function to execute on timer expiry. The callback function has function(timer_obj, params) as signature, where params is the value initially passed in options.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 with delay = 5, and initial_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]) or
copas.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) or
copas.ftp.put(requestparams)
Performs an ftp request, identical to the LuaSocket implementation, but wrapped in an async operation.
copas.ftp.get(url) or
copas.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 the copas.smtp module is a drop-in replacement for the socket.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 with max == 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.

Valid XHTML 1.0!

$Id: reference.html,v 1.16 2009/04/07 21:34:52 carregal Exp $