From 22c7d7f22dfdd67cfd8126540a1c03514ab5e2c5 Mon Sep 17 00:00:00 2001 From: zhy200308 <2258391712@qq.com> Date: Tue, 11 Aug 2026 21:39:46 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=89=AB=E7=A0=81=E5=90=8E=E5=85=88?= =?UTF-8?q?=E5=9C=A8=E5=BD=93=E5=89=8D=E7=BD=91=E7=BB=9C=E7=9B=B4=E8=BF=9E?= =?UTF-8?q?=EF=BC=8C=E4=B8=8D=E5=86=8D=E6=97=A0=E6=9D=A1=E4=BB=B6=E5=88=87?= =?UTF-8?q?=20Direct=20AP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 实测诊断给出了决定性信息:手机成功连上 Direct AP、拿到 192.168.137.200/24、网关 192.168.137.1,二维码也正确指向 192.168.137.1:39393,但那个地址上的 39393 不应答,整个 /24 扫了 253 个地址也没有。也就是说手机侧全对,是 Windows 没有在 ICS 虚拟 网卡上接受连接。 而这次切换本来就没有必要——两台设备当时已经在同一个 192.168.8.0/24 局域网里,且实测 192.168.8.68:39393 是通的。切到 Direct AP 反而引入了 ICS 虚拟网卡、该网卡独立的防火墙配置,以及实测一两分钟的配网等待。 改动 1. 二维码始终携带局域网地址(pairing.rs) 此前开 Direct AP 时只放一个 AP 地址,手机因此**必须**切网才能连。 现在无论是否开 AP 都带上常规局域网地址,多两个短地址对二维码密度 的影响可以忽略。 2. 端点顺序修正(pairing.rs) 此前无条件把 192.168.137.1 / 192.168.49.1 排在最前,即使本机根本 没有这两块网卡——手机于是先去探测两个不存在的地址,真正可用的 局域网地址被挤到后面。改为真实网卡优先、猜测性兜底地址殿后。 3. 先试当前网络(MainActivity) 扫到带 Wi-Fi 凭据的码时,先用系统默认网络并发探测二维码里的地址 (700ms 连接 / 900ms 读取)。通了就直接开始传输,完全跳过配网弹窗 与虚拟网卡;不通才切 Direct AP。新增 UploadClient.probeEndpoints。 4. 配网请求复用加时间上限(WifiConnector) 上一版为了避免「系统选网弹窗还开着就 unregister」而改成复用挂起的 请求,但没有上限。系统偶尔会让请求既不回 onAvailable 也不回 onUnavailable 地一直挂着,于是每次「重试连接」都只是再等一次那个 死掉的请求——这正是本次「配网越来越慢、至少两分钟」的由来。 超过 20 秒即推倒重来。 5. 网关探测过滤 0.0.0.0(WifiConnector) 诊断截图里出现了 http://0.0.0.0:39393,来自默认路由的空网关, 永远连不上却占着探测预算。回环与组播地址一并过滤。 Rust 侧 cargo test 40/40,含两项新用例:端点顺序、以及开 Direct AP 时 二维码仍携带局域网地址。Kotlin 侧本机无法编译,仅做结构检查。 --- .../main/java/com/qft/optical/MainActivity.kt | 41 +++++++ .../main/java/com/qft/optical/UploadClient.kt | 24 +++++ .../java/com/qft/optical/WifiConnector.kt | 14 ++- desktop/src/pairing.rs | 101 +++++++++++++++--- 4 files changed, 163 insertions(+), 17 deletions(-) diff --git a/android/app/src/main/java/com/qft/optical/MainActivity.kt b/android/app/src/main/java/com/qft/optical/MainActivity.kt index ec789ee..9dcac05 100644 --- a/android/app/src/main/java/com/qft/optical/MainActivity.kt +++ b/android/app/src/main/java/com/qft/optical/MainActivity.kt @@ -604,6 +604,47 @@ class MainActivity : ComponentActivity() { private fun connectPair(pair: PairingPayload) { val attempt = ++pairConnectionAttempt transferAbortReason = null + + // 先在**当前网络**上试一把二维码给出的地址。 + // + // 两台设备常常本来就在同一个局域网里,此时切到 Direct AP 是纯粹的 + // 倒退:要等系统配网弹窗、要走 ICS 虚拟网卡、还得让那块网卡的防火墙 + // 配置也放行,实测能耗掉一两分钟。只有当前网络确实够不着电脑时, + // 才值得付出切网的代价。 + if (pair.wifi != null && pair.endpoints.isNotEmpty()) { + showConnecting(pair, "正在当前网络上尝试直连…") + transferExecutor.execute { + val direct = UploadClient.probeEndpoints( + network = null, // 用系统默认网络,不绑定 + pairing = pair, + deviceName = receiverDeviceLabel, + endpoints = pair.endpoints, + connectMs = 700, + readMs = 900, + ) + runOnUiThread { + if (attempt != pairConnectionAttempt) return@runOnUiThread + if (direct != null) { + connectedNetwork = null // 走默认网络即可 + connectedBaseUrl = direct + updateConnectingStatus("当前网络已直连到电脑,无需切换 Wi-Fi。") + if (pair.direction == TransferDirection.DOWNLOAD_TO_PHONE) { + startDownloadFromPc(pair, direct) + } else { + showSendReady(pair, direct) + } + } else { + // 当前网络够不着,才切 Direct AP + connectViaWifi(pair, attempt) + } + } + } + return + } + connectViaWifi(pair, attempt) + } + + private fun connectViaWifi(pair: PairingPayload, attempt: Long) { showConnecting(pair, pair.wifi?.let { "正在请求连接 ${it.ssid}…" } ?: "正在使用当前局域网探测电脑…") wifiConnector.connect( pairing = pair, diff --git a/android/app/src/main/java/com/qft/optical/UploadClient.kt b/android/app/src/main/java/com/qft/optical/UploadClient.kt index a681611..730a813 100644 --- a/android/app/src/main/java/com/qft/optical/UploadClient.kt +++ b/android/app/src/main/java/com/qft/optical/UploadClient.kt @@ -159,6 +159,30 @@ object UploadClient { return null } + /** + * 在指定网络(`network` 为 null 表示系统默认网络)上并发探测一组地址, + * 返回第一个应答的。 + * + * 供「切换 Wi-Fi 之前先试当前网络」这一步使用:两台设备本来就在同一个 + * 局域网时,这一下就成功了,不必再走配网弹窗与虚拟网卡。 + */ + fun probeEndpoints( + network: Network?, + pairing: PairingPayload, + deviceName: String, + endpoints: List, + connectMs: Int, + readMs: Int, + ): String? = probeCandidatesParallel( + network = network, + pairing = pairing, + deviceName = deviceName, + candidates = endpoints, + workers = endpoints.size.coerceAtMost(8).coerceAtLeast(1), + connectMs = connectMs, + readMs = readMs, + ) + private fun probeCandidatesParallel( network: Network?, pairing: PairingPayload, diff --git a/android/app/src/main/java/com/qft/optical/WifiConnector.kt b/android/app/src/main/java/com/qft/optical/WifiConnector.kt index 3915f47..64b97d2 100644 --- a/android/app/src/main/java/com/qft/optical/WifiConnector.kt +++ b/android/app/src/main/java/com/qft/optical/WifiConnector.kt @@ -20,7 +20,11 @@ import java.net.InetAddress import java.util.concurrent.atomic.AtomicBoolean class WifiConnector(context: Context) { - private companion object { const val TAG = "QftWifi" } + private companion object { + const val TAG = "QftWifi" + /** 超过这个时长仍未出结果的配网请求视为卡死,重试时不再复用 */ + const val REUSE_WINDOW_MS = 20_000L + } private val appContext = context.applicationContext private val connectivity = appContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager private val wifiManager = appContext.getSystemService(Context.WIFI_SERVICE) as WifiManager @@ -65,7 +69,13 @@ class WifiConnector(context: Context) { // 同一个 SSID 的请求还挂在系统那里且没有终结:换掉 UI 回调即可, // 千万不要 unregister 再重新 requestNetwork。 - if (wifi != null && callback != null && pendingSsid == wifi.ssid && + // 复用必须有时间上限。系统偶尔会让一个 WifiNetworkSpecifier 请求 + // 既不回 onAvailable 也不回 onUnavailable 地一直挂着;若无条件复用, + // 用户每次点「重试连接」都只是再等一次那个死掉的请求,表现就是 + // 「配网越来越慢、几分钟都没反应」。超窗就推倒重来。 + val reusable = pendingStartedAt > 0L && + SystemClock.elapsedRealtime() - pendingStartedAt < REUSE_WINDOW_MS + if (wifi != null && callback != null && pendingSsid == wifi.ssid && reusable && pendingTerminal?.get() == false) { Log.i(TAG, "reuse outstanding request SSID=${wifi.ssid}") listener = Listener(onStatus, onAvailable, onUnavailable) diff --git a/desktop/src/pairing.rs b/desktop/src/pairing.rs index 3676680..adffd6f 100644 --- a/desktop/src/pairing.rs +++ b/desktop/src/pairing.rs @@ -54,15 +54,19 @@ impl PairingPayload { /// a long transport string/security object and only keeps a small endpoint /// fallback list. This materially lowers QR density and speeds phone scan. pub fn encode_text(&self) -> Result { - // Direct-AP pairing carries one short endpoint hint for the immediate - // happy path, while Android still treats the connected gateway + UDP - // discovery as authoritative fallbacks. One endpoint keeps QFTPAIR2 - // compact but avoids a full discovery round on common Windows APs. - let endpoints: Vec<&str> = if self.wifi.is_some() { - self.endpoints.iter().take(1).map(String::as_str).collect() - } else { - self.endpoints.iter().take(3).map(String::as_str).collect() - }; + // 开了 Direct AP 时,此前只放一个 AP 地址进二维码,手机因此**必须** + // 切到那张虚拟网卡才能连上。可两台设备本来常常已经在同一个局域网里, + // 切过去反而引入了 ICS 网卡、独立防火墙配置和几十秒的配网等待。 + // + // 现在无论是否开 Direct AP,都把常规局域网地址一并带上, + // 手机可以先在当前网络直连,连不上再切 AP。多两个短地址对 + // 二维码密度的影响可以忽略。 + let endpoints: Vec<&str> = self + .endpoints + .iter() + .take(3) + .map(String::as_str) + .collect(); let wifi = self.wifi.as_ref().map(|w| json!([w.ssid, w.passphrase])); let mut value = json!({ "v": 2, @@ -213,6 +217,16 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec { } } + // 真实存在的网卡地址排在前面,其中 Direct AP 常用的两个网段优先; + // 随后才补上猜测性的兜底地址。此前无条件把 192.168.137.1 / 49.1 排在 + // 最前,即使本机根本没有这两块网卡——手机于是先去探测两个不存在的 + // 地址,真正可用的局域网地址反而被挤到后面。 + ips.sort_by_key(|ip| { + if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 } + else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 } + else if ip.is_private() { 2 } + else { 3 } + }); for fallback in [ Ipv4Addr::new(192, 168, 137, 1), Ipv4Addr::new(192, 168, 49, 1), @@ -221,12 +235,6 @@ pub fn local_ipv4_endpoints(port: u16) -> Vec { ips.push(fallback); } } - ips.sort_by_key(|ip| { - if *ip == Ipv4Addr::new(192, 168, 137, 1) { 0 } - else if *ip == Ipv4Addr::new(192, 168, 49, 1) { 1 } - else if ip.is_private() { 2 } - else { 3 } - }); ips.into_iter() .map(|ip| format!("http://{ip}:{port}")) .collect() @@ -256,3 +264,66 @@ mod tests { assert!(text.len() < 800); } } + +#[cfg(test)] +mod endpoint_order_tests { + use super::*; + + /// 二维码里的地址顺序直接决定手机先探测谁。真实网卡必须排在 + /// 猜测性兜底地址之前,否则手机会先去连两个根本不存在的地址。 + #[test] + fn real_interfaces_come_before_guessed_fallbacks() { + let endpoints = local_ipv4_endpoints(39393); + assert!(!endpoints.is_empty(), "至少应有兜底地址"); + + let real: Vec = local_ipv4_addresses(); + let guessed = ["http://192.168.137.1:39393", "http://192.168.49.1:39393"]; + for address in &real { + let endpoint = format!("http://{address}:39393"); + let Some(position) = endpoints.iter().position(|e| *e == endpoint) else { continue }; + for guess in guessed { + // 若某个兜底地址并非本机真实网卡,它必须排在真实网卡之后 + if real.iter().any(|ip| format!("http://{ip}:39393") == guess) { continue } + if let Some(guess_position) = endpoints.iter().position(|e| e == guess) { + assert!( + position < guess_position, + "真实地址 {endpoint} 应排在猜测地址 {guess} 之前:{endpoints:?}" + ); + } + } + } + } + + #[test] + fn download_pairing_carries_lan_endpoints_even_with_direct_ap() { + // 开了 Direct AP 也要带上局域网地址,否则手机必须切网才能连 + let payload = PairingPayload { + v: 2, + session: "abcdefghijklmnopqrstuvwxyz012345".into(), + pc_name: "PC".into(), + transport: "http-parallel-v2".into(), + port: 39393, + endpoints: vec![ + "http://192.168.137.1:39393".into(), + "http://192.168.8.68:39393".into(), + ], + wifi: Some(WifiCredentials { + ssid: "QFT-PC-abc".into(), + passphrase: "0123456789ab".into(), + security: "WPA2".into(), + }), + direction: PairingDirection::Upload, + file_name: None, + file_size: None, + sha256: None, + }; + let text = payload.encode_text().unwrap(); + let json = String::from_utf8( + base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(text.trim_start_matches(PAIR_PREFIX)) + .unwrap(), + ).unwrap(); + assert!(json.contains("192.168.8.68"), "局域网地址必须进二维码:{json}"); + assert!(json.contains("192.168.137.1"), "Direct AP 地址也应保留:{json}"); + } +}