Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple connection checker for Corona SDK
---------------------------------------
-- 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
@esem1967

This comment has been minimized.

Copy link

@esem1967 esem1967 commented Oct 8, 2014

When I try running the above piece of code on Android Devices (Samsung and Sony Ericsson) I always get a status as "Connection Available" even when there is no connection.

Use the below code to invoke the test function:

local connection = require("connection")
connection.test(function (isAvailable)
if isAvailable then
print("Connection available!")
else
print("No connection :(")
end
end)

Any help appreciated - Cheers

@ataafarin

This comment has been minimized.

Copy link

@ataafarin ataafarin commented Oct 9, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.