Commit 7ef7644e authored by Mygod's avatar Mygod

Refine handling timeouts

parent 33d866ae
......@@ -23,6 +23,7 @@ package com.github.shadowsocks.net
import com.github.shadowsocks.utils.printLog
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.IOException
import java.lang.IllegalStateException
import java.nio.ByteBuffer
import java.nio.channels.*
import java.util.concurrent.ConcurrentLinkedQueue
......@@ -61,8 +62,10 @@ class ChannelMonitor : Thread("ChannelMonitor"), AutoCloseable {
suspend fun wait(channel: SelectableChannel, ops: Int) = suspendCancellableCoroutine<Unit> { cont ->
register(channel, ops) {
if (it.isValid) it.interestOps(0) // stop listening
cont.resume(Unit)
if (it.isValid) it.interestOps(0) // stop listening
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
private val monitor = ChannelMonitor()
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 {
configureBlocking(false)
......@@ -75,12 +75,8 @@ class LocalDnsServer(private val localResolver: suspend (String) -> Array<InetAd
val source = receive(buffer)!!
buffer.flip()
launch {
try {
val reply = resolve(buffer)
while (send(reply, source) <= 0) monitor.wait(this@apply, SelectionKey.OP_WRITE)
} catch (e: Exception) {
printLog(e)
}
val reply = resolve(buffer)
while (send(reply, source) <= 0) monitor.wait(this@apply, SelectionKey.OP_WRITE)
}
}
}
......
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