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 高性能锁。
|
||||
*
|
||||
|
||||
@@ -7,6 +7,38 @@ import java.nio.ByteOrder
|
||||
import java.util.zip.CRC32
|
||||
|
||||
class ProtocolTest {
|
||||
@Test
|
||||
fun routeCandidatesOnlyKeepEndpointsOnTheActiveSubnet() {
|
||||
val endpoints = listOf(
|
||||
"http://192.168.137.1:39393",
|
||||
"http://192.168.49.1:39393",
|
||||
"http://192.168.1.20:39393",
|
||||
"http://10.20.30.40:39393",
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
listOf("http://192.168.1.20:39393"),
|
||||
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
||||
)
|
||||
assertEquals(
|
||||
listOf("http://10.20.30.40:39393"),
|
||||
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("10.20.99.2" to 16)),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun routeCandidatesRejectWrongPortsAndMalformedAddresses() {
|
||||
val endpoints = listOf(
|
||||
"http://192.168.1.20:39394",
|
||||
"http://192.168.1.999:39393",
|
||||
"http://192.168.1.30:39393",
|
||||
)
|
||||
assertEquals(
|
||||
listOf("http://192.168.1.30:39393"),
|
||||
EndpointRouting.onAnySubnet(endpoints, 39393, listOf("192.168.1.88" to 24)),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun parsesPcToPhoneAutomaticDownloadPairing() {
|
||||
val json = """{"v":2,"s":"abcdefghijklmnopqrstuvwxyz012345","n":"DESKTOP-QFT","p":39393,"e":["http://192.168.49.1:39393"],"d":"d","f":"sample.bin","z":42,"h":"${"00".repeat(32)}"}"""
|
||||
|
||||
@@ -7,7 +7,8 @@ use anyhow::Context;
|
||||
use windows::{
|
||||
core::HSTRING,
|
||||
Devices::WiFiDirect::{
|
||||
WiFiDirectAdvertisementPublisher, WiFiDirectAdvertisementPublisherStatus,
|
||||
WiFiDirectAdvertisementListenStateDiscoverability, WiFiDirectAdvertisementPublisher,
|
||||
WiFiDirectAdvertisementPublisherStatus,
|
||||
},
|
||||
Security::Credentials::PasswordCredential,
|
||||
};
|
||||
@@ -32,6 +33,16 @@ impl DirectAp {
|
||||
.context("创建 Wi-Fi Direct publisher 失败")?;
|
||||
let ad = publisher.Advertisement()
|
||||
.context("读取 Wi-Fi Direct advertisement 失败")?;
|
||||
// WinRT defaults this property to `None`, which still lets the
|
||||
// publisher report `Started` but does not make the AP discoverable.
|
||||
// Android then waits in the system Wi-Fi picker until it times out,
|
||||
// exactly as if the hotspot had never been started. Intensive keeps
|
||||
// the legacy SSID discoverable even when the desktop window is not
|
||||
// foregrounded during the phone-side connection flow.
|
||||
ad.SetListenStateDiscoverability(
|
||||
WiFiDirectAdvertisementListenStateDiscoverability::Intensive,
|
||||
)
|
||||
.context("启用 QFT Wi-Fi Direct 可发现性失败")?;
|
||||
ad.SetIsAutonomousGroupOwnerEnabled(true)
|
||||
.context("启用 Autonomous Group Owner 失败")?;
|
||||
let legacy = ad.LegacySettings()
|
||||
|
||||
+14
-1
@@ -849,9 +849,22 @@ impl QftApp {
|
||||
.as_ref()
|
||||
.map(|server| server.port)
|
||||
.unwrap_or(sender::PREFERRED_PORT);
|
||||
// 宽屏下把连接信息放到防火墙右侧:这两块都是扫码失败时要一起核对的
|
||||
// 诊断信息,并排后不必在控制区里上下寻找。最小窗口下仍改回纵向,
|
||||
// 给防火墙按钮和较长的 endpoint 留出足够宽度。
|
||||
if ui.available_width() >= 860.0 {
|
||||
ui.columns(2, |cols| {
|
||||
self.firewall_panel(&mut cols[0], listen_port);
|
||||
self.send_connection_panel(&mut cols[1], listen_port);
|
||||
});
|
||||
} else {
|
||||
self.firewall_panel(ui, listen_port);
|
||||
|
||||
ui.add_space(6.0);
|
||||
self.send_connection_panel(ui, listen_port);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_connection_panel(&mut self, ui: &mut egui::Ui, listen_port: u16) {
|
||||
ui.group(|ui| {
|
||||
ui.collapsing("二维码广播的地址", |ui| {
|
||||
for endpoint in
|
||||
|
||||
@@ -452,7 +452,6 @@ fn receive_parallel_chunk(
|
||||
let mut out = OpenOptions::new().write(true).open(&part_path)?;
|
||||
out.seek(SeekFrom::Start(offset))?;
|
||||
copy_exact(reader, &mut out, content_len)?;
|
||||
out.sync_data()?;
|
||||
|
||||
let received = {
|
||||
let mut session = session_arc.lock().map_err(|_| anyhow::anyhow!("上传会话损坏"))?;
|
||||
@@ -503,6 +502,10 @@ fn finish_parallel_upload(
|
||||
)
|
||||
};
|
||||
|
||||
// Per-chunk FlushFileBuffers serializes otherwise independent upload lanes
|
||||
// and is especially costly on Windows. The in-memory session cannot resume
|
||||
// across a desktop-process crash anyway, so commit once after all chunks.
|
||||
OpenOptions::new().write(true).open(&part_path)?.sync_data()?;
|
||||
let sha = hash_file(&part_path)?;
|
||||
if final_path.exists() { bail!("目标文件已存在,请重新初始化上传") }
|
||||
fs::rename(&part_path, &final_path).context("完成文件重命名失败")?;
|
||||
|
||||
Reference in New Issue
Block a user