5 function receive (connection)
6 connection:settimeout(0)
7 local s, status = connection:receive (2^10)
8 if status == "timeout" then
9 coroutine.yield (connection)
14 function download (host, file, outfile)
15 --local f = assert (io.open (outfile, "w"))
16 local c = assert (socket.connect (host, 80))
17 c:send ("GET "..file.." HTTP/1.0\r\n\r\n")
19 local s, status = receive (c)
21 if status == "closed" then
30 function get (host, file, outfile)
31 print (string.format ("Downloading %s from %s to %s", file, host, outfile))
32 local co = coroutine.create (function ()
33 return download (host, file, outfile)
35 table.insert (threads, co)
38 function dispatcher ()
40 local n = table.getn (threads)
44 local connections = {}
46 local status, res = coroutine.resume (threads[i])
48 table.remove (threads, i)
51 table.insert (connections, res)
54 if table.getn (connections) == n then
55 socket.select (connections)
62 print (string.format ("usage: %s url [times]", arg[0]))
65 local times = arg[2] or 5
67 url = string.gsub (url, "^http.?://", "")
68 local _, _, host, file = string.find (url, "^([^/]+)(/.*)")
69 local _, _, fn = string.find (file, "([^/]+)$")
72 get (host, file, fn..i)