@@ -15,15 +15,20 @@ import io.ktor.client.request.*
15
15
import io.ktor.http.*
16
16
import io.ktor.websocket.*
17
17
import kotlinx.coroutines.CoroutineScope
18
+ import kotlinx.coroutines.delay
18
19
import kotlinx.coroutines.isActive
19
20
import kotlinx.coroutines.launch
20
21
import net.mamoe.mirai.api.http.adapter.reverse.Destination
21
22
import net.mamoe.mirai.api.http.adapter.reverse.ReverseWebsocketAdapterSetting
22
23
import net.mamoe.mirai.api.http.adapter.reverse.handleReverseWs
24
+ import net.mamoe.mirai.utils.MiraiLogger
25
+ import net.mamoe.mirai.utils.warning
23
26
import kotlin.coroutines.CoroutineContext
24
27
import kotlin.coroutines.EmptyCoroutineContext
28
+ import java.net.ConnectException
29
+ import java.net.SocketException
25
30
26
- class WsClient : CoroutineScope {
31
+ class WsClient ( private var log : MiraiLogger ) : CoroutineScope {
27
32
28
33
override val coroutineContext: CoroutineContext = EmptyCoroutineContext
29
34
@@ -33,14 +38,24 @@ class WsClient : CoroutineScope {
33
38
install(WebSockets )
34
39
}
35
40
36
- private lateinit var webSocketSession: DefaultClientWebSocketSession
41
+ private var webSocketSession: DefaultClientWebSocketSession ? = null
37
42
38
43
fun listen (destination : Destination , setting : ReverseWebsocketAdapterSetting ) {
39
44
launch {
40
- client.ws(buildWsRequest(destination, setting)) {
41
- webSocketSession = this
45
+ while (client.isActive) {
46
+ try {
47
+ client.ws(buildWsRequest(destination, setting)) {
48
+ webSocketSession = this
42
49
43
- handleReverseWs(this @WsClient)
50
+ handleReverseWs(this @WsClient)
51
+ }
52
+ } catch (_: ConnectException ) { // ignored
53
+ } catch (e: SocketException ) { // log
54
+ log.error(" [reverse-ws] SocketException occurred: ${e.localizedMessage} " )
55
+ }
56
+ webSocketSession = null
57
+ log.warning { " [reverse-ws] Connection to ${destination.host + " :" + destination.port + destination.path } interrupted. Trying reconnect in ${destination.reconnectInterval} ms." }
58
+ delay(destination.reconnectInterval)
44
59
}
45
60
}
46
61
}
@@ -51,7 +66,8 @@ class WsClient : CoroutineScope {
51
66
52
67
suspend fun send (content : String ) {
53
68
if (client.isActive) {
54
- webSocketSession.outgoing.send(Frame .Text (content))
69
+ webSocketSession?.also { it.outgoing.send(Frame .Text (content)) }
70
+ ? : log.warning { " [reverse-ws] Dropped content $content while waiting for reconnect." }
55
71
}
56
72
}
57
73
0 commit comments