Search code examples
socketsluacoronasdkluasocket

LuaSocket to test presence of internet connection


I'm trying to test the presence of an internet connection in Corona SDK, using LuaSocket library.

I found this solution:

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

But it have a problem: if there is a bad/unstable connection, the program is blocked until the socket is running (for various seconds).

So I tried like this:

    connection:settimeout(1000, 't')

But it's very inaccurate (it's returning false where there is a little network lag). There is a better way?

Maybe making the socket not blocking?

UPDATE 2: I tried this code, but I can't really understand if it makes sense...

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

It always returns "no connection"


Solution

  • You can take a look over over network.setStatusListener.

    You cannot use IP addresses with it but it seems like you don't care about that.