luasocket-3.0~rc1+git+ac3201d/ 0000775 0000000 0000000 00000000000 13025576467 0016001 5 ustar 00root root 0000000 0000000 luasocket-3.0~rc1+git+ac3201d/.gitignore 0000664 0000000 0000000 00000000144 13025576467 0017770 0 ustar 00root root 0000000 0000000 *.o
*.so
*.so.*
*.obj
*.lib
*.dll*
*.user
*.sdf
Lua.props
Debug
Release
*.manifest
*.swp
*.suo
x64
luasocket-3.0~rc1+git+ac3201d/.travis.yml 0000664 0000000 0000000 00000002665 13025576467 0020123 0 ustar 00root root 0000000 0000000 language: erlang
env:
global:
- LUAROCKS_BASE=luarocks-2.0.13
matrix:
- LUA=lua5.1 LUA_DEV=liblua5.1-dev LUA_VER=5.1 LUA_SFX=5.1 LUA_INCDIR=/usr/include/lua5.1
- LUA=lua5.2 LUA_DEV=liblua5.2-dev LUA_VER=5.2 LUA_SFX=5.2 LUA_INCDIR=/usr/include/lua5.2
- LUA=luajit LUA_DEV=libluajit-5.1-dev LUA_VER=5.1 LUA_SFX=jit LUA_INCDIR=/usr/include/luajit-2.0
branches:
only:
- master
before_install:
- if [ $LUA = "luajit" ]; then
sudo add-apt-repository ppa:mwild1/ppa -y && sudo apt-get update -y;
fi
- sudo apt-get install $LUA
- sudo apt-get install $LUA_DEV
- lua$LUA_SFX -v
# Install a recent luarocks release
- wget http://luarocks.org/releases/$LUAROCKS_BASE.tar.gz
- tar zxvpf $LUAROCKS_BASE.tar.gz
- cd $LUAROCKS_BASE
- ./configure
--lua-version=$LUA_VER --lua-suffix=$LUA_SFX --with-lua-include="$LUA_INCDIR"
- sudo make
- sudo make install
- cd $TRAVIS_BUILD_DIR
install:
- export DEBUG=DEBUG
- sudo -E luarocks make luasocket-scm-0.rockspec
script:
- cd test
- lua$LUA_SFX hello.lua
- lua$LUA_SFX testsrvr.lua > /dev/null &
- lua$LUA_SFX testclnt.lua
- lua$LUA_SFX stufftest.lua
- lua$LUA_SFX excepttest.lua
- lua$LUA_SFX test_bind.lua
- lua$LUA_SFX test_getaddrinfo.lua
- lua$LUA_SFX ltn12test.lua
- lua$LUA_SFX mimetest.lua
- lua$LUA_SFX urltest.lua
- lua$LUA_SFX test_socket_error.lua
notifications:
email:
on_success: change
on_failure: always
luasocket-3.0~rc1+git+ac3201d/FIX 0000664 0000000 0000000 00000002465 13025576467 0016361 0 ustar 00root root 0000000 0000000
http was preserving old host header during redirects
fix smtp.send hang on source error
add create field to FTP and SMTP and fix HTTP ugliness
clean timeout argument to open functions in SMTP, HTTP and FTP
eliminate globals from namespaces created by module().
url.absolute was not working when base_url was already parsed
http.request was redirecting even when the location header was empty
tcp{client}:shutdown() was checking for group instead of class.
tcp{client}:send() now returns i+sent-1...
get rid of a = socket.try() in the manual, except for protected cases. replace it with assert.
get rid of "base." kludge in package.loaded
check all "require("http")" etc in the manual.
make sure sock_gethostname.* only return success if the hp is not null!
change 'l' prefix in C libraries to 'c' to avoid clash with LHF libraries
don't forget the declarations in luasocket.h and mime.h!!!
setpeername was using udp{unconnected}
fixed a bug in http.lua that caused some requests to fail (Florian Berger)
fixed a bug in select.c that prevented sockets with descriptor 0 from working (Renato Maia)
fixed a "bug" that caused dns.toip to crash under uLinux
fixed a "bug" that caused a crash in gethostbyname under VMS
DEBUG and VERSION became _DEBUG and _VERSION
send returns the right value if input is "". Alexander Marinov
luasocket-3.0~rc1+git+ac3201d/LICENSE 0000664 0000000 0000000 00000002070 13025576467 0017005 0 ustar 00root root 0000000 0000000 LuaSocket 3.0 license
Copyright © 2004-2013 Diego Nehab
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
luasocket-3.0~rc1+git+ac3201d/Lua51.props 0000664 0000000 0000000 00000001743 13025576467 0017762 0 ustar 00root root 0000000 0000000 
IPv4 name resolution functions dns.toip and dns.tohostname return all information obtained from the resolver in a table of the form:
resolved4 = {
name = canonic-name,
alias = alias-list,
ip = ip-address-list
}
Note that the alias list can be empty.
The more general name resolution function dns.getaddrinfo, which supports both IPv6 and IPv4, returns all information obtained from the resolver in a table of the form:
resolved6 = {
[1] = {
family = family-name-1,
addr = address-1
},
...
[n] = {
family = family-name-n,
addr = address-n
}
}
Here, family contains the string "inet" for IPv4 addresses, and "inet6" for IPv6 addresses.
socket.dns.getaddrinfo(address)
Converts from host name to address.
Address can be an IPv4 or IPv6 address or host name.
The function returns a table with all information returned by the resolver. In case of error, the function returns nil followed by an error message.
socket.dns.gethostname()
Returns the standard host name for the machine as a string.
socket.dns.tohostname(address)
Converts from IPv4 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.dns.toip(address)
Converts from host name to IPv4 address.
Address can be an IP address or host name.
Returns a string with the first IP address found for 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.
luasocket-3.0~rc1+git+ac3201d/doc/ftp.html 0000664 0000000 0000000 00000022433 13025576467 0020231 0 ustar 00root root 0000000 0000000FTP (File Transfer Protocol) is a protocol used to transfer files between hosts. The ftp namespace offers thorough support to FTP, under a simple interface. The implementation conforms to RFC 959.
High level functions are provided supporting the most common operations. These high level functions are implemented on top of a lower level interface. Using the low-level interface, users can easily create their own functions to access any operation supported by the FTP protocol. For that, check the implementation.
To really benefit from this module, a good understanding of LTN012, Filters sources and sinks is necessary.
To obtain the ftp namespace, run:
-- loads the FTP module and any libraries it requires local ftp = require("socket.ftp")
URLs MUST conform to RFC 1738, that is, an URL is a string in the form:
[ftp://][<user>[:<password>]@]<host>[:<port>][/<path>][type=a|i]
The following constants in the namespace can be set to control the default behavior of the FTP module:
ftp.get(url)
ftp.get{
host = string,
sink = LTN12 sink,
argument or path = string,
[user = string,]
[password = string]
[command = string,]
[port = number,]
[type = string,]
[step = LTN12 pump step,]
[create = function]
}
The get function has two forms. The simple form has fixed functionality: it downloads the contents of a URL and returns it as a string. The generic form allows a lot more control, as explained below.
If the argument of the get function is a table, the function expects at least the fields host, sink, and one of argument or path (argument takes precedence). Host is the server to connect to. Sink is the simple LTN12 sink that will receive the downloaded data. Argument or path give the target path to the resource in the server. The optional arguments are the following:
If successful, the simple version returns the URL contents as a string, and the generic function returns 1. In case of error, both functions return nil and an error message describing the error.
-- load the ftp support local ftp = require("socket.ftp") -- Log as user "anonymous" on server "ftp.tecgraf.puc-rio.br", -- and get file "lua.tar.gz" from directory "pub/lua" as binary. f, e = ftp.get("ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz;type=i")
-- load needed modules local ftp = require("socket.ftp") local ltn12 = require("ltn12") local url = require("socket.url") -- a function that returns a directory listing function nlst(u) local t = {} local p = url.parse(u) p.command = "nlst" p.sink = ltn12.sink.table(t) local r, e = ftp.get(p) return r and table.concat(t), e end
ftp.put(url, content)
ftp.put{
host = string,
source = LTN12 sink,
argument or path = string,
[user = string,]
[password = string]
[command = string,]
[port = number,]
[type = string,]
[step = LTN12 pump step,]
[create = function]
}
The put function has two forms. The simple form has fixed functionality: it uploads a string of content into a URL. The generic form allows a lot more control, as explained below.
If the argument of the put function is a table, the function expects at least the fields host, source, and one of argument or path (argument takes precedence). Host is the server to connect to. Source is the simple LTN12 source that will provide the contents to be uploaded. Argument or path give the target path to the resource in the server. The optional arguments are the following:
Both functions return 1 if successful, or nil and an error message describing the reason for failure.
-- load the ftp support local ftp = require("socket.ftp") -- Log as user "fulano" on server "ftp.example.com", -- using password "silva", and store a file "README" with contents -- "wrong password, of course" f, e = ftp.put("ftp://fulano:silva@ftp.example.com/README", "wrong password, of course")
-- load the ftp support local ftp = require("socket.ftp") local ltn12 = require("ltn12") -- Log as user "fulano" on server "ftp.example.com", -- using password "silva", and append to the remote file "LOG", sending the -- contents of the local file "LOCAL-LOG" f, e = ftp.put{ host = "ftp.example.com", user = "fulano", password = "silva", command = "appe", argument = "LOG", source = ltn12.source.file(io.open("LOCAL-LOG", "r")) }luasocket-3.0~rc1+git+ac3201d/doc/http.html 0000664 0000000 0000000 00000026426 13025576467 0020425 0 ustar 00root root 0000000 0000000
HTTP (Hyper Text Transfer Protocol) is the protocol used to exchange information between web-browsers and servers. The http namespace offers full support for the client side of the HTTP protocol (i.e., the facilities that would be used by a web-browser implementation). The implementation conforms to the HTTP/1.1 standard, RFC 2616.
The module exports functions that provide HTTP functionality in different levels of abstraction. From the simple string oriented requests, through generic LTN12 based, down to even lower-level if you bother to look through the source code.
To obtain the http namespace, run:
-- loads the HTTP module and any libraries it requires local http = require("socket.http")
URLs must conform to RFC 1738, that is, an URL is a string in the form:
[http://][<user>[:<password>]@]<host>[:<port>][/<path>]
MIME headers are represented as a Lua table in the form:
headers = {
field-1-name = field-1-value,
field-2-name = field-2-value,
field-3-name = field-3-value,
...
field-n-name = field-n-value
}
Field names are case insensitive (as specified by the standard) and all functions work with lowercase field names (but see socket.headers.canonic). Field values are left unmodified.
Note: MIME headers are independent of order. Therefore, there is no problem in representing them in a Lua table.
The following constants can be set to control the default behavior of the HTTP module:
Note: These constants are global. Changing them will also change the behavior other code that might be using LuaSocket.
http.request(url [, body])
http.request{
url = string,
[sink = LTN12 sink,]
[method = string,]
[headers = header-table,]
[source = LTN12 source],
[step = LTN12 pump step,]
[proxy = string,]
[redirect = boolean,]
[create = function]
}
The request function has two forms. The simple form downloads a URL using the GET or POST method and is based on strings. The generic form performs any HTTP method and is LTN12 based.
If the first argument of the request function is a string, it should be an url. In that case, if a body is provided as a string, the function will perform a POST method in the url. Otherwise, it performs a GET in the url
If the first argument is instead a table, the most important fields are the url and the simple LTN12 sink that will receive the downloaded content. Any part of the url can be overridden by including the appropriate field in the request table. If authentication information is provided, the function uses the Basic Authentication Scheme (see note) to retrieve the document. If sink is nil, the function discards the downloaded data. The optional parameters are the following:
In case of failure, the function returns nil followed by an error message. If successful, the simple form returns the response body as a string, followed by the response status code, the response headers and the response status line. The generic function returns the same information, except the first return value is just the number 1 (the body goes to the sink).
Even when the server fails to provide the contents of the requested URL (URL not found, for example), it usually returns a message body (a web page informing the URL was not found or some other useless page). To make sure the operation was successful, check the returned status code. For a list of the possible values and their meanings, refer to RFC 2616.
Here are a few examples with the simple interface:
-- load the http module local io = require("io") local http = require("socket.http") local ltn12 = require("ltn12") -- connect to server "www.cs.princeton.edu" and retrieves this manual -- file from "~diego/professional/luasocket/http.html" and print it to stdout http.request{ url = "http://www.cs.princeton.edu/~diego/professional/luasocket/http.html", sink = ltn12.sink.file(io.stdout) } -- connect to server "www.example.com" and tries to retrieve -- "/private/index.html". Fails because authentication is needed. b, c, h = http.request("http://www.example.com/private/index.html") -- b returns some useless page telling about the denied access, -- h returns authentication information -- and c returns with value 401 (Authentication Required) -- tries to connect to server "wrong.host" to retrieve "/" -- and fails because the host does not exist. r, e = http.request("http://wrong.host/") -- r is nil, and e returns with value "host not found"
And here is an example using the generic interface:
-- load the http module http = require("socket.http") -- Requests information about a document, without downloading it. -- Useful, for example, if you want to display a download gauge and need -- to know the size of the document in advance r, c, h = http.request { method = "HEAD", url = "http://www.tecgraf.puc-rio.br/~diego" } -- r is 1, c is 200, and h would return the following headers: -- h = { -- date = "Tue, 18 Sep 2001 20:42:21 GMT", -- server = "Apache/1.3.12 (Unix) (Red Hat/Linux)", -- ["last-modified"] = "Wed, 05 Sep 2001 06:11:20 GMT", -- ["content-length"] = 15652, -- ["connection"] = "close", -- ["content-Type"] = "text/html" -- }
Note: When sending a POST request, simple interface adds a "Content-type: application/x-www-form-urlencoded" header to the request. This is the type used by HTML forms. If you need another type, use the generic interface.
Note: Some URLs are protected by their servers from anonymous download. For those URLs, the server must receive some sort of authentication along with the request or it will deny download and return status "401 Authentication Required".
The HTTP/1.1 standard defines two authentication methods: the Basic Authentication Scheme and the Digest Authentication Scheme, both explained in detail in RFC 2068.
The Basic Authentication Scheme sends <user> and <password> unencrypted to the server and is therefore considered unsafe. Unfortunately, by the time of this implementation, the wide majority of servers and browsers support the Basic Scheme only. Therefore, this is the method used by the toolkit whenever authentication is required.
-- load required modules http = require("socket.http") mime = require("mime") -- Connect to server "www.example.com" and tries to retrieve -- "/private/index.html", using the provided name and password to -- authenticate the request b, c, h = http.request("http://fulano:silva@www.example.com/private/index.html") -- Alternatively, one could fill the appropriate header and authenticate -- the request directly. r, c = http.request { url = "http://www.example.com/private/index.html", headers = { authorization = "Basic " .. (mime.b64("fulano:silva")) } }luasocket-3.0~rc1+git+ac3201d/doc/index.html 0000664 0000000 0000000 00000016621 13025576467 0020551 0 ustar 00root root 0000000 0000000
LuaSocket is a Lua extension library that is composed by two parts: a C core that provides support for the TCP and UDP transport layers, and a set of Lua modules that add support for functionality commonly needed by applications that deal with the Internet.
The core support has been implemented so that it is both efficient and simple to use. It is available to any Lua application once it has been properly initialized by the interpreter in use. The code has been tested and runs well on several Windows and UNIX platforms.
Among the support modules, the most commonly used implement the SMTP (sending e-mails), HTTP (WWW access) and FTP (uploading and downloading files) client protocols. These provide a very natural and generic interface to the functionality defined by each protocol. In addition, you will find that the MIME (common encodings), URL (anything you could possible want to do with one) and LTN12 (filters, sinks, sources and pumps) modules can be very handy.
The library is available under the same terms and conditions as the Lua language, the MIT license. The idea is that if you can use Lua in a project, you should also be able to use LuaSocket.
Copyright © 1999-2013 Diego Nehab. All rights reserved.
Author: Diego Nehab
LuaSocket version 3.0-rc1 is now available for download! It is compatible with Lua 5.1 and 5.2, and has been tested on Windows XP, Linux, and Mac OS X. Chances are it works well on most UNIX distributions and Windows flavors.
The current version of the library can be found at the LuaSocket project page on GitHub. Besides the full C and Lua source code for the library, the distribution contains several examples, this user's manual and basic test procedures.
Take a look at the installation section of the manual to find out how to properly install the library.
This marks the first release of LuaSocket that wholeheartedly embraces the open-source development philosophy. After a long hiatus, Matthew Wild finally convinced me it was time for a release including IPv6 and Lua 5.2 support. It was more work than we anticipated. Special thanks to Sam Roberts, Florian Zeitz, and Paul Aurich, Liam Devine, Alexey Melnichuk, and everybody else that has helped bring this library back to life.
Main changes for LuaSocket 3.0-rc1 are IPv6 support and Lua 5.2 compatibility.
All previous versions of the LuaSocket library can be downloaded here. Although these versions are no longer supported, they are still available for those that have compatibility issues.
luasocket-3.0~rc1+git+ac3201d/doc/installation.html 0000664 0000000 0000000 00000007453 13025576467 0022146 0 ustar 00root root 0000000 0000000Here we describe the standard distribution. If the standard doesn't meet your needs, we refer you to the Lua discussion list, where any question about the package scheme will likely already have been answered.
On Unix systems, the standard distribution uses two base directories, one for system dependent files, and another for system independent files. Let's call these directories <CDIR> and <LDIR>, respectively. For example, in my laptp, Lua 5.1 is configured to use '/usr/local/lib/lua/5.1' for <CDIR> and '/usr/local/share/lua/5.1' for <LDIR>. On Windows, <CDIR> usually points to the directory where the Lua executable is found, and <LDIR> points to a lua/ directory inside <CDIR>. (These settings can be overridden by environment variables LUA_PATH and LUA_CPATH. See the Lua documentation for details.) Here is the standard LuaSocket distribution directory structure:
<LDIR>/ltn12.lua <LDIR>/socket.lua <CDIR>/socket/core.dll <LDIR>/socket/http.lua <LDIR>/socket/tp.lua <LDIR>/socket/ftp.lua <LDIR>/socket/smtp.lua <LDIR>/socket/url.lua <LDIR>/mime.lua <CDIR>/mime/core.dll
Naturally, on Unix systems, core.dll would be replaced by core.so.
With the above setup, and an interpreter with shared library support, it should be easy to use LuaSocket. Just fire the interpreter and use the require function to gain access to whatever module you need:
Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio > socket = require("socket") > print(socket._VERSION) --> LuaSocket 3.0-rc1
Each module loads their dependencies automatically, so you only need to load the modules you directly depend upon:
Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio > http = require("socket.http") > print(http.request("http://www.impa.br/~diego/software/luasocket")) --> homepage gets dumped to terminalluasocket-3.0~rc1+git+ac3201d/doc/introduction.html 0000664 0000000 0000000 00000030221 13025576467 0022153 0 ustar 00root root 0000000 0000000
LuaSocket is a Lua extension library that is composed by two parts: a C core that provides support for the TCP and UDP transport layers, and a set of Lua modules that add support for the SMTP (sending e-mails), HTTP (WWW access) and FTP (uploading and downloading files) protocols and other functionality commonly needed by applications that deal with the Internet. This introduction is about the C core.
Communication in LuaSocket is performed via I/O objects. These can represent different network domains. Currently, support is provided for TCP and UDP, but nothing prevents other developers from implementing SSL, Local Domain, Pipes, File Descriptors etc. I/O objects provide a standard interface to I/O across different domains and operating systems.
The API design had two goals in mind. First, users experienced with the C API to sockets should feel comfortable using LuaSocket. Second, the simplicity and the feel of the Lua language should be preserved. To achieve these goals, the LuaSocket API keeps the function names and semantics the C API whenever possible, but their usage in Lua has been greatly simplified.
One of the simplifications is the receive pattern capability. Applications can read data from stream domains (such as TCP) line by line, block by block, or until the connection is closed. All I/O reads are buffered and the performance differences between different receive patterns are negligible.
Another advantage is the flexible timeout control mechanism. As in C, all I/O operations are blocking by default. For example, the send, receive and accept methods of the TCP domain will block the caller application until the operation is completed (if ever!). However, with a call to the settimeout method, an application can specify upper limits on the time it can be blocked by LuaSocket (the "total" timeout), on the time LuaSocket can internally be blocked by any OS call (the "block" timeout) or a combination of the two. Each LuaSocket call might perform several OS calls, so that the two timeout values are not equivalent.
Finally, the host name resolution is transparent, meaning that most functions and methods accept both IP addresses and host names. In case a host name is given, the library queries the system's resolver and tries the main IP address returned. Note that direct use of IP addresses is more efficient, of course. The toip and tohostname functions from the DNS module are provided to convert between host names and IP addresses.
Together, these changes make network programming in LuaSocket much simpler than it is in C, as the following sections will show.
TCP (Transfer Control Protocol) is reliable stream protocol. In other words, applications communicating through TCP can send and receive data as an error free stream of bytes. Data is split in one end and reassembled transparently on the other end. There are no boundaries in the data transfers. The library allows users to read data from the sockets in several different granularities: patterns are available for lines, arbitrary sized blocks or "read up to connection closed", all with good performance.
The library distinguishes three types of TCP sockets: master, client and server sockets.
Master sockets are newly created TCP sockets returned by the function socket.tcp. A master socket is transformed into a server socket after it is associated with a local address by a call to the bind method followed by a call to the listen. Conversely, a master socket can be changed into a client socket with the method connect, which associates it with a remote address.
On server sockets, applications can use the accept method to wait for a client connection. Once a connection is established, a client socket object is returned representing this connection. The other methods available for server socket objects are getsockname, setoption, settimeout, and close.
Client sockets are used to exchange data between two applications over the Internet. Applications can call the methods send and receive to send and receive data. The other methods available for client socket objects are getsockname, getpeername, setoption, settimeout, shutdown, and close.
Example:
A simple echo server, using LuaSocket. The program binds to an ephemeral port (one that is chosen by the operating system) on the local host and awaits client connections on that port. When a connection is established, the program reads a line from the remote end and sends it back, closing the connection immediately. You can test it using the telnet program.
-- load namespace local socket = require("socket") -- create a TCP socket and bind it to the local host, at any port local server = assert(socket.bind("*", 0)) -- find out which port the OS chose for us local ip, port = server:getsockname() -- print a message informing what's up print("Please telnet to localhost on port " .. port) print("After connecting, you have 10s to enter a line to be echoed") -- loop forever waiting for clients while 1 do -- wait for a connection from any client local client = server:accept() -- make sure we don't block waiting for this client's line client:settimeout(10) -- receive the line local line, err = client:receive() -- if there was no error, send it back to the client if not err then client:send(line .. "\n") end -- done with client, close the object client:close() end
UDP (User Datagram Protocol) is a non-reliable datagram protocol. In other words, applications communicating through UDP send and receive data as independent blocks, which are not guaranteed to reach the other end. Even when they do reach the other end, they are not guaranteed to be error free. Data transfers are atomic, one datagram at a time. Reading only part of a datagram discards the rest, so that the following read operation will act on the next datagram. The advantages are in simplicity (no connection setup) and performance (no error checking or error correction).
Note that although no guarantees are made, these days networks are so good that, under normal circumstances, few errors happen in practice.
An UDP socket object is created by the socket.udp function. UDP sockets do not need to be connected before use. The method sendto can be used immediately after creation to send a datagram to IP address and port. Host names are not allowed because performing name resolution for each packet would be forbiddingly slow. Methods receive and receivefrom can be used to retrieve datagrams, the latter returning the IP and port of the sender as extra return values (thus being slightly less efficient).
When communication is performed repeatedly with a single peer, an application should call the setpeername method to specify a permanent partner. Methods sendto and receivefrom can no longer be used, but the method send can be used to send data directly to the peer, and the method receive will only return datagrams originating from that peer. There is about 30% performance gain due to this practice.
To associate an UDP socket with a local address, an application calls the setsockname method before sending any datagrams. Otherwise, the socket is automatically bound to an ephemeral address before the first data transmission and once bound the local address cannot be changed. The other methods available for UDP sockets are getpeername, getsockname, settimeout, setoption and close.
Example:
A simple daytime client, using LuaSocket. The program connects to a remote server and tries to retrieve the daytime, printing the answer it got or an error message.
-- change here to the host an port you want to contact local host, port = "localhost", 13 -- load namespace local socket = require("socket") -- convert host name to ip address local ip = assert(socket.dns.toip(host)) -- create a new UDP object local udp = assert(socket.udp()) -- contact daytime host assert(udp:sendto("anything", ip, port)) -- retrieve the answer and print results io.write(assert(udp:receive()))
Although not covered in the introduction, LuaSocket offers much more than TCP and UDP functionality. As the library evolved, support for HTTP, FTP, and SMTP were built on top of these. These modules and many others are covered by the reference manual.
luasocket-3.0~rc1+git+ac3201d/doc/ltn12.html 0000664 0000000 0000000 00000025270 13025576467 0020402 0 ustar 00root root 0000000 0000000The ltn12 namespace implements the ideas described in LTN012, Filters sources and sinks. This manual simply describes the functions. Please refer to the LTN for a deeper explanation of the functionality provided by this module.
To obtain the ltn12 namespace, run:
-- loads the LTN21 module local ltn12 = require("ltn12")
ltn12.filter.chain(filter1, filter2 [, ... filterN])
Returns a filter that passes all data it receives through each of a series of given filters.
Filter1 to filterN are simple filters.
The function returns the chained filter.
The nesting of filters can be arbitrary. For instance, the useless filter below doesn't do anything but return the data that was passed to it, unaltered.
-- load required modules local ltn12 = require("ltn12") local mime = require("mime") -- create a silly identity filter id = ltn12.filter.chain( mime.encode("quoted-printable"), mime.encode("base64"), mime.decode("base64"), mime.decode("quoted-printable") )
ltn12.filter.cycle(low [, ctx, extra])
Returns a high-level filter that cycles though a low-level filter by passing it each chunk and updating a context between calls.
Low is the low-level filter to be cycled, ctx is the initial context and extra is any extra argument the low-level filter might take.
The function returns the high-level filter.
-- load the ltn12 module local ltn12 = require("ltn12") -- the base64 mime filter factory encodet['base64'] = function() return ltn12.filter.cycle(b64, "") end
ltn12.pump.all(source, sink)
Pumps all data from a source to a sink.
If successful, the function returns a value that evaluates to true. In case of error, the function returns a false value, followed by an error message.
ltn12.pump.step(source, sink)
Pumps one chunk of data from a source to a sink.
If successful, the function returns a value that evaluates to true. In case of error, the function returns a false value, followed by an error message.
ltn12.sink.chain(filter, sink)
Creates and returns a new sink that passes data through a filter before sending it to a given sink.
ltn12.sink.error(message)
Creates and returns a sink that aborts transmission with the error message.
ltn12.sink.file(handle, message)
Creates a sink that sends data to a file.
Handle is a file handle. If handle is nil, message should give the reason for failure.
The function returns a sink that sends all data to the given handle and closes the file when done, or a sink that aborts the transmission with the error message
In the following example, notice how the prototype is designed to fit nicely with the io.open function.
-- load the ltn12 module local ltn12 = require("ltn12") -- copy a file ltn12.pump.all( ltn12.source.file(io.open("original.png", "rb")), ltn12.sink.file(io.open("copy.png", "wb")) )
ltn12.sink.null()
Returns a sink that ignores all data it receives.
ltn12.sink.simplify(sink)
Creates and returns a simple sink given a fancy sink.
ltn12.sink.table([table])
Creates a sink that stores all chunks in a table. The chunks can later be efficiently concatenated into a single string.
Table is used to hold the chunks. If nil, the function creates its own table.
The function returns the sink and the table used to store the chunks.
-- load needed modules local http = require("socket.http") local ltn12 = require("ltn12") -- a simplified http.get function function http.get(u) local t = {} local respt = request{ url = u, sink = ltn12.sink.table(t) } return table.concat(t), respt.headers, respt.code end
ltn12.source.cat(source1 [, source2, ..., sourceN])
Creates a new source that produces the concatenation of the data produced by a number of sources.
Source1 to sourceN are the original sources.
The function returns the new source.
ltn12.source.chain(source, filter)
Creates a new source that passes data through a filter before returning it.
The function returns the new source.
ltn12.source.empty()
Creates and returns an empty source.
ltn12.source.error(message)
Creates and returns a source that aborts transmission with the error message.
ltn12.source.file(handle, message)
Creates a source that produces the contents of a file.
Handle is a file handle. If handle is nil, message should give the reason for failure.
The function returns a source that reads chunks of data from given handle and returns it to the user, closing the file when done, or a source that aborts the transmission with the error message
In the following example, notice how the prototype is designed to fit nicely with the io.open function.
-- load the ltn12 module local ltn12 = require("ltn12") -- copy a file ltn12.pump.all( ltn12.source.file(io.open("original.png", "rb")), ltn12.sink.file(io.open("copy.png", "wb")) )
ltn12.source.simplify(source)
Creates and returns a simple source given a fancy source.
ltn12.source.string(string)
Creates and returns a source that produces the contents of a string, chunk by chunk.
luasocket-3.0~rc1+git+ac3201d/doc/lua05.ppt 0000664 0000000 0000000 00001122000 13025576467 0020215 0 ustar 00root root 0000000 0000000 ÐÏࡱá > þÿ Ü â þÿÿÿ à ß Þ Ý ü ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ © @ £n ÿý? " d ÿ d @ ÿÿï ÿÿÿÿÿÿ @@ `` €€ ð˜ ð È q ä 7 7 % . " $ &