fix(receiver): 收敛控制通道握手失败日志并加入指数退避重连
- 握手阶段 EOF/超时/重置包装为 HandshakeException,日志给出可读原因(主控端未开监听/正在重启/只接受一路连接) - 连接失败从 Log.e 降级为 Log.w 并去抖(首次 + 每 10 次),不再刷堆栈 - 重连改为指数退避 500ms→5s,握手成功后立即恢复快速重连 - 忽略指向本机 IP 的信标回包,避免无意义的自连握手失败循环
This commit is contained in:
1 parent
0cff2b011a
commit
993097df00
2 files changed
+100
-11
No files matched your search
@@ -248,6 +248,16 @@ class ReceiverSession(
|
||||
private fun connectWhenHostReady() {
|
||||
while (running) {
|
||||
val target = hostOverride.ifBlank { HostBeacon.lastHost }
|
||||
// 连自己是无意义的:只会立刻被关闭,并刷出一堆握手失败日志。
|
||||
if (target.isNotEmpty() && target == selfAddress) {
|
||||
Log.w(TAG, "主控端地址指向本机($target),忽略")
|
||||
try {
|
||||
Thread.sleep(2000)
|
||||
} catch (_: InterruptedException) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (target.isNotEmpty() && transport == null) {
|
||||
val created = ReceiverTransport(
|
||||
target,
|
||||
@@ -322,6 +332,9 @@ class ReceiverSession(
|
||||
return intArrayOf(w.coerceAtLeast(16) and 1.inv(), h.coerceAtLeast(16) and 1.inv())
|
||||
}
|
||||
|
||||
/** 本机局域网 IPv4,用于过滤「连自己」的信标回包。 */
|
||||
private val selfAddress: String by lazy { runCatching { localIp }.getOrDefault("") }
|
||||
|
||||
private val localIp: String
|
||||
get() = java.net.NetworkInterface.getNetworkInterfaces().toList()
|
||||
.flatMap { it.inetAddresses.toList() }
|
||||
|
||||
+87
-11
@@ -37,8 +37,25 @@ class ReceiverTransport(
|
||||
private val clipboard: ClipboardBridge,
|
||||
private val fileService: FileService,
|
||||
) {
|
||||
companion object {
|
||||
private const val TAG = "ReceiverTransport"
|
||||
|
||||
/** 握手成功过(链路可用)时的重连间隔。 */
|
||||
private const val INITIAL_RETRY_MS = 500L
|
||||
|
||||
/** 连续失败时的最大退避间隔。 */
|
||||
private const val MAX_RETRY_MS = 5000L
|
||||
}
|
||||
|
||||
/** 握手阶段失败:对端未就绪/已断开,属于可预期情况。 */
|
||||
private class HandshakeException(message: String, cause: Throwable) :
|
||||
Exception(message, cause)
|
||||
|
||||
private val executor = Executors.newFixedThreadPool(2)
|
||||
private val crypto = SessionCrypto()
|
||||
|
||||
/** 连续失败次数,仅用于日志去抖(只在连接线程内读写)。 */
|
||||
private var consecutiveFailures = 0
|
||||
private var socket: Socket? = null
|
||||
private var output: DataOutputStream? = null
|
||||
private var udp: DatagramSocket? = null
|
||||
@@ -68,17 +85,26 @@ class ReceiverTransport(
|
||||
if (active) return
|
||||
active = true
|
||||
executor.execute {
|
||||
var retryDelayMs = INITIAL_RETRY_MS
|
||||
while (active) {
|
||||
var handshakeDone = false
|
||||
try {
|
||||
connectAndRun()
|
||||
handshakeDone = connectAndRun()
|
||||
} catch (error: Exception) {
|
||||
Log.e("ReceiverTransport", "Failed to connect or handshake", error)
|
||||
if (active) logConnectFailure(error)
|
||||
} finally {
|
||||
resetConnection()
|
||||
}
|
||||
if (!active) break
|
||||
// 握手成功过说明链路是通的,短暂等待即可重连;一直失败则指数退避,
|
||||
// 避免主控端没启动时每 2 秒刷一次连接/握手日志。
|
||||
retryDelayMs = if (handshakeDone) {
|
||||
INITIAL_RETRY_MS
|
||||
} else {
|
||||
minOf(retryDelayMs * 2, MAX_RETRY_MS)
|
||||
}
|
||||
try {
|
||||
Thread.sleep(2000)
|
||||
Thread.sleep(retryDelayMs)
|
||||
} catch (_: InterruptedException) {
|
||||
break
|
||||
}
|
||||
@@ -86,7 +112,8 @@ class ReceiverTransport(
|
||||
}
|
||||
}
|
||||
|
||||
private fun connectAndRun() {
|
||||
/** @return 是否完成过 ECDH 握手。 */
|
||||
private fun connectAndRun(): Boolean {
|
||||
val raw = Socket().apply {
|
||||
tcpNoDelay = true
|
||||
soTimeout = 5000
|
||||
@@ -97,16 +124,64 @@ class ReceiverTransport(
|
||||
val input = DataInputStream(raw.inputStream)
|
||||
|
||||
// ECDH 握手:先发本地公钥,再读取对端 65 字节公钥。
|
||||
output?.write(crypto.publicBytes)
|
||||
output?.flush()
|
||||
val peerPublic = ByteArray(65)
|
||||
input.readFully(peerPublic)
|
||||
keys = crypto.deriveKeys(peerPublic)
|
||||
// 对端在这期间关闭连接(主控端未开监听、正在重启、或只接受一路连接)都属于
|
||||
// 可预期情况,单独包一层异常,日志里给出人能看懂的原因。
|
||||
try {
|
||||
output?.write(crypto.publicBytes)
|
||||
output?.flush()
|
||||
val peerPublic = ByteArray(65)
|
||||
input.readFully(peerPublic)
|
||||
keys = crypto.deriveKeys(peerPublic)
|
||||
} catch (error: Exception) {
|
||||
throw HandshakeException(describeHandshakeFailure(error), error)
|
||||
}
|
||||
|
||||
udp = DatagramSocket()
|
||||
running = true
|
||||
Log.i("ReceiverTransport", "Connected to $host:$controlPort")
|
||||
consecutiveFailures = 0
|
||||
Log.i(TAG, "已连接主控端 $host:$controlPort")
|
||||
readLoop(input)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun describeHandshakeFailure(error: Exception): String = when (error) {
|
||||
is java.io.EOFException -> "主控端在握手阶段关闭了连接(未开启监听或正在重启)"
|
||||
is java.net.SocketTimeoutException -> "等待主控端公钥超时"
|
||||
is java.net.SocketException -> "握手期间连接被重置: ${error.message}"
|
||||
else -> "握手失败: ${error.javaClass.simpleName} ${error.message ?: ""}".trim()
|
||||
}
|
||||
|
||||
/**
|
||||
* 连接/握手失败日志。
|
||||
*
|
||||
* 这类失败在主控端没启动、正在重启、或同时只接受一路连接时是常态,
|
||||
* 用 warn 级别并做去抖(首次 + 每 10 次),避免把可预期情况刷成 Error。
|
||||
*/
|
||||
private fun logConnectFailure(error: Exception) {
|
||||
++consecutiveFailures
|
||||
val expected = error is HandshakeException ||
|
||||
error is java.net.ConnectException ||
|
||||
error is java.net.SocketTimeoutException ||
|
||||
error is java.io.EOFException ||
|
||||
error is java.net.SocketException
|
||||
if (!expected) {
|
||||
// 非预期异常(例如密钥派生、内存问题)保留完整堆栈。
|
||||
Log.e(TAG, "控制通道异常 $host:$controlPort", error)
|
||||
return
|
||||
}
|
||||
if (consecutiveFailures == 1 || consecutiveFailures % 10 == 0) {
|
||||
val reason = (error as? HandshakeException)?.message
|
||||
?: when (error) {
|
||||
is java.net.ConnectException -> "主控端未监听控制端口"
|
||||
is java.net.SocketTimeoutException -> "连接主控端超时"
|
||||
is java.io.EOFException -> "主控端关闭了连接"
|
||||
else -> "网络异常: ${error.message ?: ""}".trim()
|
||||
}
|
||||
Log.w(
|
||||
TAG,
|
||||
"$reason($host:$controlPort),第 $consecutiveFailures 次失败,稍后重试",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun resetConnection() {
|
||||
@@ -223,7 +298,8 @@ class ReceiverTransport(
|
||||
}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
Log.w("ReceiverTransport", "Control channel ended: $error")
|
||||
// 主控端关闭是正常断线,属于可恢复状态,交给外层重连。
|
||||
Log.i(TAG, "控制通道断开: ${error.javaClass.simpleName} ${error.message ?: ""}".trim())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user