Skip to content

Instantly share code, notes, and snippets.

@nagolove
Last active August 9, 2019 09:31
Show Gist options
  • Save nagolove/fdaf491a849b5fa338dfa7d49c7b3505 to your computer and use it in GitHub Desktop.
Save nagolove/fdaf491a849b5fa338dfa7d49c7b3505 to your computer and use it in GitHub Desktop.
local socket = require 'socket'
function dispatch ()
local i = 1
local timedout = {}
while true do
if threads[i] == nil then
-- больше нет нитей?
if threads[1] == nil then break end
i = 1
-- перезапускает цикл
timedout = {}
end
local status, res = coroutine.resume(threads[i])
if not res then
-- нить выполнила свою задачу?
table.remove(threads, i)
else
-- превышено время ожидания
i = i + 1
timedout[#timedout + 1] = res
if #timedout == #threads then
-- все нити заблокированы?
socket.select(timedout)
end
end
end
end
function download (host, fileName)
local c = assert(socket.connect(host, 80))
local count = 0 -- counts number of bytes read
c:send("GET " .. fileName .. " HTTP/1.0\r\n\r\n")
print("fileName", getName(fileName))
local newFile = io.open(getName(fileName), "w")
while true do
local s, status = receive(c)
newFile:write(s)
count = count + #s
if status == "closed" then break end
end
f:close()
c:close()
print(fileName, count)
end
function receive (connection)
connection:settimeout(0)
-- не блокирует данные
local s, status, partial = connection:receive(2^10)
if status == "timeout" then
coroutine.yield(connection)
end
return s or partial, status
end
threads = {}
-- список всех живых нитей
function get (host, file)
-- создает сопрограмму
local co = coroutine.create(function ()
download(host, file)
end)
-- вставляет ее в список
table.insert(threads, co)
end
function getName(fname)
local _, second = string.match(fname, "(.+)/(.+)")
return second
end
function matchTest()
print(getName("/TR/html401/html40.txt"))
print(getName("/TR/2002/REC-xhtml1-20020801/xhtml1.pdf"))
print(getName("/TR/REC-html32.html"))
print(getName("/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt"))
end
for k, v in pairs(arg) do
if v == "--match-test" then matchTest() os.exit(0)
elseif v == "--help" then
print("Use --match-test parameter to run string.match tests")
print("Use --help to see this text")
os.exit(0)
end
end
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")
dispatch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment