如何检查非阻塞 luasocket 客户端是否丢失了连接?

How to check if a nonblocking luasocket client has lost it's connection?

我正在为 OBS 编写 Lua 脚本,它通过 TCP 连接不断从 ProPresenter(另一个程序)接收数据。我使用 LuaSocket 库建立连接,并按预期获得数据。

问题是,当我关闭 ProPresenter 时,我无法让我的脚本注册连接已关闭,同时我将 luasocket 超时设置为 0(因为它是非阻塞连接)。我需要脚本始终是非阻塞的,否则它会导致所有 OBS 停滞并且帧率降至 1 以下...

但是,如果我将超时设置为例如。 1 秒后,luasocket 注册连接已顺利关闭,根据 this 示例,当超时为 0 时它也应该工作。但显然它没有,我怀疑这是因为该示例使用了旧版本的 Luasocket,而最新版本可能已经更改。

这是我的代码:

没有注册连接因超时而关闭:

function recv_and_process_data()
    local data 

    data, err, partial = s:receive()

    if data ~= nil then
        --process the recieved data. This part works.
    elseif err == "closed" then
        --doesn't get here because of timeout...
        --inform script that the connection has closed
    elseif err == "timeout" then
        --goes here as soon as ProPresenter is closed
        print(err .. " partial: " .. partial) 
    end
end

连接关闭时注册,但使 OBS 停止:

function recv_and_process_data()
    local data 

    s:settimeout(1) --timeout set to 1 second
    data, err, partial = s:receive()
    s:settimeout(0)

    if data ~= nil then
        --process the recieved data. This part works.
    elseif err == "closed" then
        --goes here when ProPresenter is closed
        --inform script that the connection has closed
    elseif err == "timeout" then
        print(err .. " partial: " .. partial)
    end
end

这也不起作用(如建议here):

function recv_and_process_data()
    local data 

    data, err, partial = s:receive(0)
    if err == "closed" then
        print(err .. " partial: " .. partial)
    end
end

如果我无法正常工作,我想我必须尝试重新连接以查看 ProPresenters 服务器是否仍然 运行。

我也在想办法解决这个问题。我发现一个非常小的 settimeout() 值仍然是 returns 您可以使用的错误,但根本不会阻止程序运行。

我用local Data, Error = Client:settimeout(0.0001)