修复 websocket 在关闭时被关闭两次的问题

This commit is contained in:
czp3009 2019-03-25 18:36:48 +08:00
parent acc1a308ef
commit 408c1ecff8
4 changed files with 12 additions and 5 deletions

View File

@ -472,7 +472,7 @@ onClose = { liveClient, closeReason ->
如果数据包被中间人修改, 那么可能不会触发 `onConnect` 回调, 但是会触发 `onClose`.
如果手动取消了执行 `start()` 方法的协程将不会触发 `onClose`.
如果手动取消了执行 `start()` 方法的协程将不会触发 `onClose`.
## 发送直播弹幕
在直播间里发送弹幕也非常简单(必须先登陆)

View File

@ -9,7 +9,6 @@ import io.ktor.client.features.websocket.WebSockets
import io.ktor.client.features.websocket.wss
import io.ktor.http.cio.websocket.CloseReason
import io.ktor.http.cio.websocket.WebSocketSession
import io.ktor.http.cio.websocket.close
import io.ktor.util.InternalAPI
import io.ktor.util.KtorExperimentalAPI
import io.ktor.util.decodeString
@ -155,9 +154,10 @@ class LiveClient(
/**
* 关闭连接
*/
suspend fun close() = websocketSession?.run {
fun close() = websocketSession?.run {
websocketSession = null
close(CloseReason(CloseReason.Codes.NORMAL, "user close"))
//client 不能使用 close(), 因为 WebsocketSession 本体执行完毕时会自动执行一次 close(), 这会导致多次关闭
incoming.cancel()
} ?: Unit
/**

View File

@ -15,6 +15,8 @@ enum class PacketType(val value: Int) {
ENTER_ROOM_RESPONSE(8);
companion object {
fun getByValue(value: Int) = values().firstOrNull { it.value == value } ?: UNKNOWN
private val byValueMap = PacketType.values().associateBy { it.value }
fun getByValue(value: Int) = byValueMap[value] ?: UNKNOWN
}
}

View File

@ -20,6 +20,11 @@ class LiveClientTest {
sendUserOnlineHeart = true,
onConnect = {
println("Connected")
//想要这么做的人一定逻辑学有问题
// launch {
// delay(5_000)
// it.close()
// }
},
onPopularityPacket = { _, popularity ->
println("Current popularity: $popularity")