Lua http socket evaluation 的翻译为:Lua HTTP套接字评估。

我使用 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

原文链接 https://stackoverflow.com/questions/6015540

点赞
stackoverflow用户703016
stackoverflow用户703016

是的,就像这样:

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

if response == nil then
    print('无法连接服务器:\n'..URL)
    return
end

-- 在这里编写你当请求成功时要执行的内容

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

2011-05-16 09:52:20
stackoverflow用户34799
stackoverflow用户34799

更妙的是,当请求失败时,第二个返回值就是失败的原因:

在失败的情况下,该函数返回 nil,紧接着是错误信息。

(摘自 http.request 的文档

因此,您可以直接从套接字直接打印出问题:

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

if response == nil then
    -- httpCode 变量和错误信息相同
    print(httpCode)
    return
end

-- 在请求成功时执行操作
2011-05-16 17:50:21