Skip to content

Commit

Permalink
wait net with CountDownLatch
Browse files Browse the repository at this point in the history
  • Loading branch information
rikaaa0928 committed Oct 14, 2024
1 parent b89e731 commit d0dc576
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions app/src/main/java/moe/rikaaa0928/uot/UogClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import java.net.DatagramSocket
import java.net.InetAddress
import java.net.SocketTimeoutException
import java.net.URL
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
Expand All @@ -30,7 +31,7 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br
var req: Channel<Udp.UdpReq>? = null
var udpSocket: AtomicReference<DatagramSocket?> = AtomicReference(null);
private val stop = AtomicBoolean(true)
private val noNet = AtomicBoolean(false)
private val waitNet: AtomicReference<CountDownLatch> = AtomicReference(null)
private var lastAddr = ""
private var lastPort = 0
private val bufferSize = 65535;
Expand Down Expand Up @@ -115,7 +116,7 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br
Log.e("UpgClient", "grpc write", e)
break
} else {
if (noNet.get()) {
if (waitNet.get() != null) {
Log.d("UogClient", "udp receive break no net: $id")
break
}
Expand All @@ -135,8 +136,9 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br
} catch (e: Exception) {
Log.e("UogClient", "all", e)
} finally {
if (noNet.get()) {
TimeUnit.SECONDS.sleep(3)
val l = waitNet.get()
if (l != null) {
l.await()
} else {
TimeUnit.SECONDS.sleep(1)
}
Expand Down Expand Up @@ -180,9 +182,10 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
}
if (!isWifiConnected && !isMobileDataConnected) {
noNet.set(true)
waitNet.compareAndSet(null, CountDownLatch(1))
} else {
noNet.set(false)
val l = waitNet.getAndSet(null)
l?.countDown()
}
}
}
Expand Down

0 comments on commit d0dc576

Please sign in to comment.