lua程序设计(第四版)练习答案自做(第二十六章)

#!/usr/bin/lua
local socket=require"socket"
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
function download(host,file)
	local c=assert(socket.connect(host,80))
	local count=0
	local request=string.format("GET %s HTTP/1.0\r\nhost: %s\r\n\r\n",host,file)
	c:send(request)
	while true do
		local s,status=receive(c)
		count=count+#s
		if status=="closed" then
			break
		end
	end
	c:close()
	print(file,count)
end
tasks={}
function get(host,file)
	local co=coroutine.wrap(function ()
		download(host,file)
	end)
	table.insert(tasks,co)
end
--[[
function dispatch()
	local i=1
	while true do
		if tasks[i]==nil then
			if tasks[1]==nil then
				break
			end
			i=1
		end
		local res=tasks[i]()
		if not res then
			table.remove(tasks,i)
		else
			i=i+1
		end
	end
end
--]]
function dispatch()
	local i=1
	local timeout={}
	while true do
		if tasks[i]==nil then
			if tasks[1]==nil then
				break
			end
			i=1
			timeout={}
		end
		local res=tasks[i]()
		if not res then
			table.remove(tasks,i)
		else
			i=i+1
			timeout[#timeout+1]=res
			if #timeout==#tasks then
				socket.select(timeout)
			end
		end
	end
end
get("www.lua.org","/ftp/lua-5.3.2.tar.gz")
get("www.lua.org","/ftp/lua-5.3.1.tar.gz")
dispatch()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值