lua - Download large file with LuaSocket's HTTP module while keeping UI responsive -
i utilize luasocket's http module download big file while displaying progress in console , later on in gui. ui must never block, not when server unresponsive during transfer. additionally, creating worker thread handle download not option.
here's got far:
local io = io local ltn12 = require("ltn12") local http = require("socket.http") local fileurl = "http://www.example.com/big_file.zip" local fileout_path = "big_file.zip" local file_size = 0 local file_down = 0 -- counter filter used in ltn12 function counter(chunk) if chunk == nil homecoming nil elseif chunk == "" homecoming "" else file_down = file_down + #chunk ui_update(file_size, file_down) -- update ui, run main ui loop etc. homecoming chunk -- homecoming unmodified chunk end end -- first request -- determine file size local r, c, h = http.request { method = "head", url = fileurl } file_size = h["content-length"] -- sec request -- download file r, c, h = http.request { method = "get", url = fileurl, -- set our chain, count first write file sink = ltn12.sink.chain( counter, ltn12.sink.file(io.open(fileout_path, "w")) ) }
there few problems above, ignoring error checking , hard-coding:
it requires 2 http requests when possible 1 (a normal request sends content-length) if server unresponsive, ui unresponsive, filter gets called when there info process.how making sure ui never blocks?
there illustration on non-preemptive multithreading in programming in lua uses non-blocking luasocket calls , coroutines multiple parallel downloads. should possible apply same logic process avoid blocking. can add together should consider calling logic idle event in gui (if there such thing) avoid getting "attempt yield across metamethod/c-call boundary" errors.
http lua luasocket
No comments:
Post a Comment