Use single thread for reading packet, fix #557

This commit is contained in:
Him188 2020-09-15 10:29:51 +08:00
parent db588f949f
commit 0294df4700

View File

@ -10,6 +10,7 @@
package net.mamoe.mirai.qqandroid.utils package net.mamoe.mirai.qqandroid.utils
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlinx.io.core.ByteReadPacket import kotlinx.io.core.ByteReadPacket
import kotlinx.io.core.Closeable import kotlinx.io.core.Closeable
@ -20,6 +21,7 @@ import java.io.BufferedInputStream
import java.io.BufferedOutputStream import java.io.BufferedOutputStream
import java.net.Socket import java.net.Socket
import java.net.SocketException import java.net.SocketException
import java.util.concurrent.Executors
import kotlin.coroutines.CoroutineContext import kotlin.coroutines.CoroutineContext
/** /**
@ -38,6 +40,7 @@ internal actual class PlatformSocket : Closeable {
if (::socket.isInitialized) { if (::socket.isInitialized) {
socket.close() socket.close()
} }
thread.shutdownNow()
} }
@PublishedApi @PublishedApi
@ -67,15 +70,17 @@ internal actual class PlatformSocket : Closeable {
} }
} }
private val thread = Executors.newSingleThreadExecutor()
/** /**
* @throws ReadPacketInternalException * @throws ReadPacketInternalException
*/ */
actual suspend fun read(): ByteReadPacket { actual suspend fun read(): ByteReadPacket = suspendCancellableCoroutine { cont ->
return withContext(Dispatchers.IO) { thread.submit {
try { kotlin.runCatching {
readChannel.readPacketAtMost(Long.MAX_VALUE) readChannel.readPacketAtMost(Long.MAX_VALUE)
} catch (e: IOException) { }.let {
throw ReadPacketInternalException(e) cont.resumeWith(it)
} }
} }
} }