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)

すべてが期待どおりに機能しますが、リクエストは 2 回実行されます。次のようなことができるのだろうか(明らかに機能しません):

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

さらに良いことに、リクエストが失敗した場合、2 番目のリターンが理由です。

失敗した場合、関数は 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 に答える