Skip to content

Commit

Permalink
add suspendable api
Browse files Browse the repository at this point in the history
  • Loading branch information
raheemadamboev committed May 8, 2022
1 parent f81a4cd commit 94c04e1
Showing 1 changed file with 24 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,22 @@ import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class CheckInternet {

companion object {
private const val HOST_NAME = "8.8.8.8"
private const val PORT = 53
private const val TIMEOUT = 1_500
}

fun check(listener: (connected: Boolean) -> Unit) {
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
try {
val socket = Socket()
socket.connect(InetSocketAddress("8.8.8.8", 53), 1500)
socket.connect(InetSocketAddress(HOST_NAME, PORT), TIMEOUT)
socket.close()
withContext(Dispatchers.Main) {
listener(true)
Expand All @@ -26,4 +34,19 @@ class CheckInternet {
}
}
}

suspend fun check(): Boolean {
return suspendCoroutine { continuation ->
CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) {
try {
val socket = Socket()
socket.connect(InetSocketAddress(HOST_NAME, PORT), TIMEOUT)
socket.close()
continuation.resume(true)
} catch (e: IOException) {
continuation.resume(false)
}
}
}
}
}

0 comments on commit 94c04e1

Please # to comment.