<html>
<head><title>Programming in Lua - Code Examples</title></head>
<body bgcolor="#ffffff">
<pre>
require "luasocket"
--<em> warning: depending on the version of luasocket that we use,</em>
--<em> we have to change `settimeout' to `timeout' (as done here)</em>
<b>function</b> receive (connection)
connection:timeout(0) --<em> do not block</em>
<b>local</b> s, status = connection:receive(2^10)
<b>if</b> status == "timeout" <b>then</b>
coroutine.yield(connection)
<b>end</b>
<b>return</b> s, status
<b>end</b>
<b>function</b> download (host, file)
<b>local</b> c = assert(socket.connect(host, 80))
<b>local</b> count = 0 --<em> counts number of bytes read</em>
c:send("GET " .. file .. " HTTP/1.0\r\n\r\n")
<b>while</b> <b>true</b> <b>do</b>
<b>local</b> s, status = receive(c)
count = count + string.len(s)
<b>if</b> status == "closed" <b>then</b> <b>break</b> <b>end</b>
<b>end</b>
c:close()
print(file, count)
<b>end</b>
threads = {} --<em> list of all live threads</em>
<b>function</b> get (host, file)
--<em> create coroutine</em>
<b>local</b> co = coroutine.create(<b>function</b> ()
download(host, file)
<b>end</b>)
--<em> insert it in the list</em>
table.insert(threads, co)
<b>end</b>
<b>function</b> dispatcher ()
<b>while</b> <b>true</b> <b>do</b>
<b>local</b> n = table.getn(threads)
<b>if</b> n == 0 <b>then</b> <b>break</b> <b>end</b> --<em> no more threads to run</em>
<b>local</b> connections = {}
<b>for</b> i=1,n <b>do</b>
<b>local</b> status, res = coroutine.resume(threads[i])
<b>if</b> <b>not</b> res <b>then</b> --<em> thread finished its task?</em>
table.remove(threads, i)
<b>break</b>
<b>else</b> --<em> timeout</em>
table.insert(connections, res)
<b>end</b>
<b>end</b>
<b>if</b> table.getn(connections) == n <b>then</b>
socket.select(connections)
<b>end</b>
<b>end</b>
<b>end</b>
host = "www.w3.org"
get(host, "/TR/html401/html40.txt")
get(host,"/TR/2002/REC-xhtml1-20020801/xhtml1.pdf")
get(host,"/TR/REC-html32.html")
get(host, "/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt")
dispatcher() --<em> main loop</em>
</pre>
</body>
</html>
- 1
- 2
- 3
前往页