sockets - LuaSocket 用于测试互联网连接是否存在

标签 sockets lua coronasdk luasocket

我正在尝试使用 LuaSocket 库测试 Corona SDK 中是否存在互联网连接。

我找到了这个解决方案:

function test()           
    local connection = socket.tcp()
    connection:settimeout(1000)
    local result = connection:connect("www.google.com", 80)
    connection:close()
    if (result) then return true end
    return false
end

但它有一个问题:如果连接不良/不稳定,程序将被阻塞,直到套接字运行(持续不同的秒数)。

所以我尝试这样:

    connection:settimeout(1000, 't')

但它非常不准确(当网络有一点延迟时它会返回 false)。有更好的办法吗?

也许让套接字不阻塞?

更新2: 我尝试了这段代码,但我无法真正理解它是否有意义......

local socket = require("socket") 
function test(callback, timeout)
    if timeout == nil then timeout = 1000 end
    local connection = socket.tcp()
    connection:settimeout(0)
    connection:connect("www.google.com", 80)
    local t
    t = timer.performWithDelay( 10, function()
        local r = socket.select({connection}, nil, 0)
        if r[1] or timeout == 0 then
            connection:close()
            timer.cancel( t )
            callback(timeout > 0)
        end
        timeout = timeout - 10
    end , 0)
end

它总是返回“无连接”

最佳答案

最后我找到了一种让它在所有设备上运行的方法。感谢hades2510:

---------------------------------------
-- Test connection to the internet
---------------------------------------
local socket = require("socket")

local connection = {}
local function manual_test(callback, timeout)
    if timeout == nil then timeout = 1000 end
    local connection = assert(socket.tcp())
    connection:settimeout(0)
    local result = connection:connect("www.google.com", 80)
    local t
    t = timer.performWithDelay( 10, function()
        local r, w, e = socket.select(nil, {connection}, 0)
        if w[1] or timeout == 0 then
            connection:close()
            timer.cancel( t )
            callback(timeout > 0)
        end
        timeout = timeout - 10
    end , 0)
end
local isReachable = nil
function connection.test(callback)
    if network.canDetectNetworkStatusChanges then
        if isReachable == nil then
            local function networkListener(event)
                isReachable = event.isReachable
                callback(isReachable)
            end
            network.setStatusListener( "www.google.com", networkListener )
        else
            callback(isReachable)
        end
    else
        manual_test(callback)
    end
end
return connection

https://gist.github.com/ProGM/9786014

关于sockets - LuaSocket 用于测试互联网连接是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22639282/

相关文章:

c++ - 连接到smtp服务器windows C++

sockets - 运行时 addeventlistener 使用 Corona 减慢 Lua 中的应用程序显示

lua - 使用 love.graphics.draw 参数进行编码。获取异常 "bad argument #1 to ' draw'(Drawable expected, got nil)"

lua - 尝试调用类方法时出错 : attempt to index local 'self' (a nil value) - Lua

android - 2d 手机游戏

timer - 电晕 : timer. 取消()返回 "Attempt to index a nil value"

c - 如何从C中的recv()读取提取参数和有效负载?

python - 如何检测套接字断开连接?/如何超时调用 socket.recv?

connect() 到外部 IP 不工作

ios - Corona SDK system.orientation 在 iPhone 上返回错误的值?