suppot httpc.timeout

This commit is contained in:
Cloud Wu
2016-09-24 12:28:57 +08:00
parent 18bc3216ae
commit ccb0e1b24c
2 changed files with 17 additions and 1 deletions

View File

@@ -1,3 +1,4 @@
local skynet = require "skynet"
local socket = require "http.sockethelper"
local url = require "http.url"
local internal = require "http.internal"
@@ -88,6 +89,7 @@ function httpc.dns(server,port)
end
function httpc.request(method, host, url, recvheader, header, content)
local timeout = httpc.timeout -- get httpc.timeout before any blocked api
local hostname, port = host:match"([^:]+):?(%d*)$"
if port == "" then
port = 80
@@ -98,8 +100,21 @@ function httpc.request(method, host, url, recvheader, header, content)
hostname = dns.resolve(hostname)
end
local fd = socket.connect(hostname, port)
local finish
if timeout then
skynet.timeout(timeout, function()
if not finish then
local temp = fd
fd = nil
socket.close(temp)
end
end)
end
local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content)
socket.close(fd)
finish = true
if fd then -- may close by skynet.timeout
socket.close(fd)
end
if ok then
return statuscode, body
else

View File

@@ -4,6 +4,7 @@ local dns = require "dns"
skynet.start(function()
httpc.dns() -- set dns server
httpc.timeout = 100 -- set timeout 1 second
print("GET baidu.com")
local respheader = {}
local status, body = httpc.get("baidu.com", "/", respheader)