1

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

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
4

2 回答 2

6

是的,像这样:

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

请求只会发送一次,如果失败,函数将退出。

于 2011-05-16T09:52:20.850 回答
1

更好的是,当请求失败时,第二次返回是原因:

在失败的情况下,该函数返回 nil 后跟一条错误消息。

(来自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
于 2011-05-16T17:50:21.300 回答