fix: improve QR direct connection reliability and speed
This commit is contained in:
@@ -584,6 +584,11 @@ object DownloadClient {
|
||||
} finally {
|
||||
pool.shutdownNow()
|
||||
}
|
||||
// Flushing every parallel range serializes the workers on Android's
|
||||
// storage barrier and can make Wi-Fi look much slower than it is. One
|
||||
// barrier after all ranges preserves the completed-file durability;
|
||||
// SHA-256 still rejects and re-downloads an interrupted/corrupt cache.
|
||||
RandomAccessFile(partial, "rw").use { it.fd.sync() }
|
||||
if (!ledger.allComplete()) {
|
||||
error("并行下载未完成:${ledger.bytesComplete()}/$expectedSize")
|
||||
}
|
||||
@@ -691,7 +696,6 @@ object DownloadClient {
|
||||
while (bytes.hasRemaining()) channel.write(bytes)
|
||||
received += n.toLong()
|
||||
}
|
||||
channel.force(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.qft.optical
|
||||
|
||||
import java.net.URI
|
||||
|
||||
/** Pure IPv4 routing helpers kept Android-free so candidate selection is testable. */
|
||||
object EndpointRouting {
|
||||
fun onAnySubnet(
|
||||
endpoints: List<String>,
|
||||
expectedPort: Int,
|
||||
localLinks: List<Pair<String, Int>>,
|
||||
): List<String> {
|
||||
val subnets = localLinks.mapNotNull { (address, prefix) ->
|
||||
ipv4(address)?.let { it to prefix.coerceIn(0, 32) }
|
||||
}
|
||||
if (subnets.isEmpty()) return emptyList()
|
||||
|
||||
return endpoints.filter { endpoint ->
|
||||
val uri = try { URI(endpoint) } catch (_: Exception) { return@filter false }
|
||||
if (uri.scheme != "http" || uri.port != expectedPort) return@filter false
|
||||
val candidate = ipv4(uri.host ?: return@filter false) ?: return@filter false
|
||||
subnets.any { (local, prefix) -> sameSubnet(local, candidate, prefix) }
|
||||
}.distinct()
|
||||
}
|
||||
|
||||
private fun sameSubnet(a: Long, b: Long, prefix: Int): Boolean {
|
||||
if (prefix == 0) return true
|
||||
val mask = (0xFFFF_FFFFL shl (32 - prefix)) and 0xFFFF_FFFFL
|
||||
return (a and mask) == (b and mask)
|
||||
}
|
||||
|
||||
private fun ipv4(value: String): Long? {
|
||||
val parts = value.split('.')
|
||||
if (parts.size != 4) return null
|
||||
var result = 0L
|
||||
for (part in parts) {
|
||||
val octet = part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null
|
||||
result = (result shl 8) or octet.toLong()
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -612,21 +612,27 @@ class MainActivity : ComponentActivity() {
|
||||
// 倒退:要等系统配网弹窗、要走 ICS 虚拟网卡、还得让那块网卡的防火墙
|
||||
// 配置也放行,实测能耗掉一两分钟。只有当前网络确实够不着电脑时,
|
||||
// 才值得付出切网的代价。
|
||||
if (pair.wifi != null && pair.endpoints.isNotEmpty()) {
|
||||
val currentCandidates = if (pair.wifi != null) {
|
||||
wifiConnector.currentWifiCandidates(pair.endpoints, pair.port)
|
||||
} else null
|
||||
if (currentCandidates != null && currentCandidates.endpoints.isNotEmpty()) {
|
||||
showConnecting(pair, "正在当前网络上尝试直连…")
|
||||
transferExecutor.execute {
|
||||
val direct = UploadClient.probeEndpoints(
|
||||
network = null, // 用系统默认网络,不绑定
|
||||
network = currentCandidates.network,
|
||||
pairing = pair,
|
||||
deviceName = receiverDeviceLabel,
|
||||
endpoints = pair.endpoints,
|
||||
connectMs = 700,
|
||||
readMs = 900,
|
||||
endpoints = currentCandidates.endpoints,
|
||||
connectMs = 320,
|
||||
readMs = 450,
|
||||
)
|
||||
runOnUiThread {
|
||||
if (attempt != pairConnectionAttempt) return@runOnUiThread
|
||||
if (direct != null) {
|
||||
connectedNetwork = null // 走默认网络即可
|
||||
// The probe was explicitly bound to this Wi-Fi handle;
|
||||
// keep subsequent upload/download requests on the same
|
||||
// route instead of assuming Android made it the default.
|
||||
connectedNetwork = currentCandidates.network
|
||||
connectedBaseUrl = direct
|
||||
updateConnectingStatus("当前网络已直连到电脑,无需切换 Wi-Fi。")
|
||||
if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) {
|
||||
@@ -662,6 +668,11 @@ class MainActivity : ComponentActivity() {
|
||||
transferExecutor.execute {
|
||||
if (attempt != pairConnectionAttempt) return@execute
|
||||
val gateways = wifiConnector.gatewayEndpoints(network, pair.port)
|
||||
val routedEndpoints = wifiConnector.endpointsOnNetwork(
|
||||
network,
|
||||
pair.endpoints,
|
||||
pair.port,
|
||||
)
|
||||
|
||||
// 先直接打网关。Direct AP 场景下网关**必然**就是那台电脑
|
||||
// (手机的 IP 是电脑的 DHCP 发的),根本不需要先做发现。
|
||||
@@ -672,7 +683,7 @@ class MainActivity : ComponentActivity() {
|
||||
network = network,
|
||||
pairing = pair,
|
||||
deviceName = receiverDeviceLabel,
|
||||
endpoints = (gateways + pair.endpoints).distinct(),
|
||||
endpoints = (gateways + routedEndpoints).distinct(),
|
||||
connectMs = 400,
|
||||
readMs = 600,
|
||||
)
|
||||
@@ -698,7 +709,7 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
val base = direct ?: UploadClient.probeRobust(
|
||||
network = network,
|
||||
pairing = pair,
|
||||
pairing = pair.copy(endpoints = routedEndpoints),
|
||||
deviceName = receiverDeviceLabel,
|
||||
preferredEndpoints = gateways,
|
||||
discoveredEndpoint = discovered,
|
||||
|
||||
@@ -35,6 +35,8 @@ class WifiConnector(context: Context) {
|
||||
private var legacyPreviousNetworkId: Int? = null
|
||||
private var legacyTargetNetworkId: Int? = null
|
||||
|
||||
data class EndpointCandidates(val network: Network, val endpoints: List<String>)
|
||||
|
||||
/**
|
||||
* 回调经由这个可替换的收件人转发,而不是被 NetworkCallback 闭包捕获。
|
||||
* 这样「用户点重试」时可以直接换掉 UI 回调、继续复用那个还挂着的
|
||||
@@ -316,6 +318,28 @@ class WifiConnector(context: Context) {
|
||||
|
||||
private fun hasIpv4(props: LinkProperties?): Boolean = props?.linkAddresses?.any { it.address is Inet4Address } == true
|
||||
|
||||
/**
|
||||
* Only probe QR endpoints that can actually be routed over the phone's
|
||||
* current Wi-Fi. This avoids spending a full TCP timeout on Direct-AP and
|
||||
* stale LAN addresses before Android has even started switching networks.
|
||||
*/
|
||||
fun currentWifiCandidates(endpoints: List<String>, port: Int): EndpointCandidates? {
|
||||
val network = bestWifiNetwork() ?: return null
|
||||
return EndpointCandidates(network, endpointsOnNetwork(network, endpoints, port))
|
||||
}
|
||||
|
||||
fun endpointsOnNetwork(network: Network?, endpoints: List<String>, port: Int): List<String> {
|
||||
if (network == null) return emptyList()
|
||||
val links = connectivity.getLinkProperties(network)?.linkAddresses
|
||||
?.mapNotNull { link ->
|
||||
val address = link.address as? Inet4Address ?: return@mapNotNull null
|
||||
val text = address.hostAddress ?: return@mapNotNull null
|
||||
text to link.prefixLength
|
||||
}
|
||||
.orEmpty()
|
||||
return EndpointRouting.onAnySubnet(endpoints, port, links)
|
||||
}
|
||||
|
||||
/**
|
||||
* 传输期间持有的 Wi-Fi 高性能锁。
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user