Skip to content

Commit

Permalink
retry connect implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
MrXiaoM committed Jan 7, 2024
1 parent b52acf1 commit 3a893c5
Showing 1 changed file with 28 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import cn.evolvefield.onebot.client.handler.EventBus
import cn.evolvefield.onebot.client.util.ActionSendUtils
import com.google.gson.JsonSyntaxException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.java_websocket.client.WebSocketClient
Expand All @@ -31,6 +33,7 @@ class WSClient(
val retryRestMills: Long = 60000L,
header: Map<String, String> = mapOf(),
) : WebSocketClient(uri, header) {
private var retryCount = 0
private var eventBus: EventBus? = null
fun createBot(): Bot {
return Bot(this, actionHandler)
Expand All @@ -40,6 +43,31 @@ class WSClient(
return if (eventBus != null) eventBus!! else EventBus().also { eventBus = it }
}

override fun connectBlocking(): Boolean {
if (retryTimes < 1) return super.connectBlocking()
return runBlocking {
val wait = 0L.coerceAtLeast(retryWaitMills)
val waitFormatted = String.format("%.1f", wait / 1000.0)
val restFormatted = String.format("%.1f", 0L.coerceAtLeast(retryRestMills) / 1000.0)
while (!super.connectBlocking()) {
if (retryCount >= retryTimes) {
if (retryRestMills < 0) {
logger.warn("重连 $retryTimes 次失败,放弃连接")
return@runBlocking false
}
logger.warn("重连 $retryTimes 次失败,将在 $restFormatted 秒后再尝试连接")
delay(retryRestMills)
retryCount = 0
continue
}
logger.warn("连接失败,将在 $waitFormatted 秒后尝试第 ${++retryCount} 次重连")
delay(wait)
}
retryCount = 0
return@runBlocking true
}
}

override fun onOpen(handshakedata: ServerHandshake) {
logger.info("▌ 已连接到服务器 ┈━═☆")
}
Expand Down

0 comments on commit 3a893c5

Please sign in to comment.