Commit 7ef7644e authored by Mygod's avatar Mygod

Refine handling timeouts

parent 33d866ae
...@@ -23,6 +23,7 @@ package com.github.shadowsocks.net ...@@ -23,6 +23,7 @@ package com.github.shadowsocks.net
import com.github.shadowsocks.utils.printLog import com.github.shadowsocks.utils.printLog
import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.IOException import java.io.IOException
import java.lang.IllegalStateException
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.nio.channels.* import java.nio.channels.*
import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ConcurrentLinkedQueue
...@@ -61,8 +62,10 @@ class ChannelMonitor : Thread("ChannelMonitor"), AutoCloseable { ...@@ -61,8 +62,10 @@ class ChannelMonitor : Thread("ChannelMonitor"), AutoCloseable {
suspend fun wait(channel: SelectableChannel, ops: Int) = suspendCancellableCoroutine<Unit> { cont -> suspend fun wait(channel: SelectableChannel, ops: Int) = suspendCancellableCoroutine<Unit> { cont ->
register(channel, ops) { register(channel, ops) {
if (it.isValid) it.interestOps(0) // stop listening if (it.isValid) it.interestOps(0) // stop listening
cont.resume(Unit) try {
cont.resume(Unit)
} catch (_: IllegalStateException) { } // already resumed by a timeout, maybe should use tryResume?
} }
} }
......
...@@ -65,7 +65,7 @@ class LocalDnsServer(private val localResolver: suspend (String) -> Array<InetAd ...@@ -65,7 +65,7 @@ class LocalDnsServer(private val localResolver: suspend (String) -> Array<InetAd
private val monitor = ChannelMonitor() private val monitor = ChannelMonitor()
private val job = SupervisorJob() private val job = SupervisorJob()
override val coroutineContext = Dispatchers.Default + job override val coroutineContext = Dispatchers.Default + job + CoroutineExceptionHandler { _, t -> printLog(t) }
fun start(listen: SocketAddress) = DatagramChannel.open().apply { fun start(listen: SocketAddress) = DatagramChannel.open().apply {
configureBlocking(false) configureBlocking(false)
...@@ -75,12 +75,8 @@ class LocalDnsServer(private val localResolver: suspend (String) -> Array<InetAd ...@@ -75,12 +75,8 @@ class LocalDnsServer(private val localResolver: suspend (String) -> Array<InetAd
val source = receive(buffer)!! val source = receive(buffer)!!
buffer.flip() buffer.flip()
launch { launch {
try { val reply = resolve(buffer)
val reply = resolve(buffer) while (send(reply, source) <= 0) monitor.wait(this@apply, SelectionKey.OP_WRITE)
while (send(reply, source) <= 0) monitor.wait(this@apply, SelectionKey.OP_WRITE)
} catch (e: Exception) {
printLog(e)
}
} }
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment