2011-05-16 36 views
1

我使用lua 5.1和luaSocket 2.0.2-4从Web服务器检索页面。我首先检查服务器是否正在响应,然后将Web服务器响应分配给lua变量。Lua http socket评估

local mysocket = require("socket.http") 
if mysocket.request(URL) == nil then 
    print('The server is unreachable on:\n'..URL) 
    return 
end 
local response, httpCode, header = mysocket.request(URL) 

一切正常,但请求被执行两次。我不知道如果我可以做喜欢的事(这并不明显工作):

local mysocket = require("socket.http") 
if (local response, httpCode, header = mysocket.request(URL)) == nil then 
    print('The server is unreachable on:\n'..URL) 
    return 
end 

回答

5

是的,是这样的:

local mysocket = require("socket.http") 
local response, httpCode, header = mysocket.request(URL) 

if response == nil then 
    print('The server is unreachable on:\n'..URL) 
    return 
end 

-- here you do your stuff that's supposed to happen when request worked 

请求将只发送一次,和功能将退出,如果它失败。

+0

这将做到这一点。感谢闪电般的快速回答。 – ripat 2011-05-16 10:01:17

1

更好的是,当请求失败,第二复位的原因是:

在故障的情况下,该函数返回nil后跟一个错误消息。

(从the documentation for http.request

所以,你可以直接从插座的嘴打印问题:

local http = require("socket.http") 
local response, httpCode, header = http.request(URL) 

if response == nil then 
    -- the httpCode variable contains the error message instead 
    print(httpCode) 
    return 
end 

-- here you do your stuff that's supposed to happen when request worked 
+1

@Heandel:不,httpCode会保存套接字错误信息。请参阅引文。 – 2011-05-16 18:11:49