2011-05-16 40 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