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

时间:2018-09-16 19:18:54

标签: tcp lua luasocket

我正在为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服务器是否仍在运行。

1 个答案:

答案 0 :(得分:0)

我也试图找出这个问题。我发现很小的settimeout()值仍会返回一个错误,您可以使用该错误,但根本无法阻止该程序。

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