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