Skip to content

Instantly share code, notes, and snippets.

@ProGM
Last active April 5, 2021 07:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ProGM/9786014 to your computer and use it in GitHub Desktop.
Save ProGM/9786014 to your computer and use it in GitHub Desktop.
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
Copy link

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

@arash9900
Copy link

@nodecentral
Copy link

Hi, how do I run this piece of code ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment