diff --git a/lualib/http/httpc.lua b/lualib/http/httpc.lua index 68d3ce9c..16a52823 100644 --- a/lualib/http/httpc.lua +++ b/lualib/http/httpc.lua @@ -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 diff --git a/test/testhttp.lua b/test/testhttp.lua index 76a5a4da..e66d6c19 100644 --- a/test/testhttp.lua +++ b/test/testhttp.lua @@ -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)