fix(sender): 修复断开后重连一直超时,串流窗口按被控端比例开局

- rust_core: stop 先关闭控制连接再 join 监听线程,保证端口真正释放
- rust_core: start 前回收残留线程,按 AddrInUse 重试绑定,失败不再静默
- rust_core: 监听套接字异常时把 running 置回 false;半开握手读超时缩到 1.2s
- rust_core: 新增 demo_reconnect 回归测试(stop 后立刻 start 仍可接入)
- flutter_sender: connect 检查本机监听结果,失败直接提示端口被占用
- flutter_sender: 断开时一并关闭独立串流窗口,重连不再残留旧帧
- flutter_sender: openWindow 传入被控端分辨率,窗口开局即按竖屏比例居中
This commit is contained in:
tongtong committed 2026-11-27 12:06:57 +08:00
1 parent 77ce882397
commit 32e7ca26d8
7 files changed
+269 -33

No files matched your search

+12 -3
View File
@@ -118,7 +118,10 @@ class SenderBridge {
final native = _native;
if (native != null) {
// 先确保本机控制/媒体端口在监听,再让被控端立刻拨号(不必等它下次广播)。
native.startDemoServer();
// 监听失败必须显式报错:否则被控端拨号会没人接,界面只能笼统地等到超时。
if (!native.startDemoServer()) {
throw Exception('本机监听启动失败(TCP 41001 / UDP 41000、41002 可能被占用)');
}
if (device.ip.isNotEmpty) {
native.discoveryConnect(device.ip);
}
@@ -281,9 +284,15 @@ class SenderBridge {
}
/// 把串流画面弹出为独立原生窗口(Windows);返回是否成功。
Future<bool> openVideoWindow() async {
///
/// [width] / [height] 是被控端屏幕尺寸提示:传了就按该比例开局,
/// 不再先弹出一个 16:9 的大窗口等首帧再缩回去。
Future<bool> openVideoWindow({int? width, int? height}) async {
try {
final opened = await _video.invokeMethod<bool>('openWindow');
final arguments = (width != null && height != null && width > 0 && height > 0)
? <String, dynamic>{'width': width, 'height': height}
: null;
final opened = await _video.invokeMethod<bool>('openWindow', arguments);
return opened ?? false;
} on MissingPluginException {
return false;
+23 -1
View File
@@ -215,7 +215,11 @@ class _HomePageState extends State<HomePage> {
});
try {
if (!_videoWindowOpen) {
final opened = await _bridge.openVideoWindow();
final size = _deviceScreenSize();
final opened = await _bridge.openVideoWindow(
width: size?.$1,
height: size?.$2,
);
if (!mounted) return;
if (!opened) {
_snack('当前平台不支持独立串流窗口');
@@ -230,6 +234,17 @@ class _HomePageState extends State<HomePage> {
}
}
/// 被控端屏幕尺寸(发现信标里的 `res`,如 "1080x2400");拿不到时返回 null。
(int, int)? _deviceScreenSize() {
final text = (_selected?.resolution ?? '').trim();
final match = RegExp(r'^(\d+)\s*[xX*]\s*(\d+)$').firstMatch(text);
if (match == null) return null;
final width = int.tryParse(match.group(1)!);
final height = int.tryParse(match.group(2)!);
if (width == null || height == null || width <= 0 || height <= 0) return null;
return (width, height);
}
/// 用户关掉独立串流窗口(点关闭按钮 / 按 ESC)→ 直接停止投屏。
///
/// 两个入口都会走到这里:原生的 `windowClosed` 回调,以及轮询 `stats.windowOpen`
@@ -428,6 +443,13 @@ class _HomePageState extends State<HomePage> {
Future<void> _disconnect() async {
_diagnosticLog.write('disconnect requested');
_connectWatchdog?.cancel();
// 断开时连串流窗口一起关掉,否则重连后窗口还挂在那儿显示上一路的旧帧。
if (_videoWindowOpen) {
_stopSentForWindowClose = true;
await _bridge.closeVideoWindow();
_videoWindowOpen = false;
_lastFrameAt = null;
}
await _bridge.disconnect();
if (!mounted) return;
setState(() => _phase = ConnectionPhase.idle);
@@ -895,8 +895,30 @@ class VideoTexturePlugin : public flutter::Plugin {
}
if (call.method_name() == "openWindow") {
auto store = frames_;
// Flutter 侧带上被控端屏幕尺寸,窗口首帧之前就能按正确比例开好。
int hint_width = 0;
int hint_height = 0;
if (const auto* arguments =
std::get_if<flutter::EncodableMap>(call.arguments())) {
auto read_int = [arguments](const char* key) -> int {
const auto entry = arguments->find(flutter::EncodableValue(key));
if (entry == arguments->end()) {
return 0;
}
if (const auto* value = std::get_if<int32_t>(&entry->second)) {
return *value;
}
if (const auto* value = std::get_if<int64_t>(&entry->second)) {
return static_cast<int>(*value);
}
return 0;
};
hint_width = read_int("width");
hint_height = read_int("height");
}
const bool opened = video_window_.Open(
[store](int* width, int* height) { return store->Snapshot(width, height); });
[store](int* width, int* height) { return store->Snapshot(width, height); },
hint_width, hint_height);
result->Success(flutter::EncodableValue(opened));
return;
}
+60 -17
View File
@@ -16,6 +16,33 @@ constexpr UINT kMsgApplyAspect = WM_APP + 0x52;
constexpr int kMinClientWidth = 320;
constexpr int kMinClientHeight = 180;
// 窗口最多占工作区的这个比例,竖屏串流也不会铺满整个屏幕。
constexpr double kMaxWorkAreaFraction = 0.8;
// 未知被控端尺寸时的兜底比例(常见手机竖屏 9:16)。
constexpr double kDefaultAspect = 9.0 / 16.0;
// 按比例算出「不超过工作区 80%、不小于最小值」的客户区尺寸。
void FitClientSize(double aspect, const RECT& work, int* client_width,
int* client_height) {
const int work_width = (std::max)(1, static_cast<int>(work.right - work.left));
const int work_height =
(std::max)(1, static_cast<int>(work.bottom - work.top));
const int max_width = static_cast<int>(work_width * kMaxWorkAreaFraction);
const int max_height = static_cast<int>(work_height * kMaxWorkAreaFraction);
int width = max_height > 0
? static_cast<int>(static_cast<double>(max_height) * aspect)
: max_height;
int height = max_height;
if (width > max_width) {
width = max_width;
height = static_cast<int>(static_cast<double>(width) / aspect);
}
*client_width = (std::max)(width, kMinClientWidth);
*client_height = (std::max)(height, kMinClientHeight);
}
} // namespace
VideoWindow::VideoWindow() = default;
@@ -24,7 +51,7 @@ VideoWindow::~VideoWindow() {
Close();
}
bool VideoWindow::Open(FrameProvider provider) {
bool VideoWindow::Open(FrameProvider provider, int hint_width, int hint_height) {
provider_ = std::move(provider);
if (hwnd_ != nullptr) {
ShowWindow(hwnd_, SW_SHOWNORMAL);
@@ -51,20 +78,42 @@ bool VideoWindow::Open(FrameProvider provider) {
// 不提供最大化按钮:画面窗口只按视频比例缩放。
const DWORD style = WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX;
RECT rect = {0, 0, 1280, 720};
// 被控端屏幕尺寸已知时直接按它的比例开局,竖屏手机不会被开成横向大窗。
double aspect = kDefaultAspect;
if (hint_width > 0 && hint_height > 0) {
aspect = static_cast<double>(hint_width) / static_cast<double>(hint_height);
}
RECT work = {0, 0, 1280, 720};
if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &work, 0)) {
work = RECT{0, 0, GetSystemMetrics(SM_CXSCREEN),
GetSystemMetrics(SM_CYSCREEN)};
}
int client_width = 0;
int client_height = 0;
FitClientSize(aspect, work, &client_width, &client_height);
RECT rect = {0, 0, client_width, client_height};
AdjustWindowRect(&rect, style, FALSE);
HWND hwnd = CreateWindowExW(
0, kWindowClass, kWindowTitle, style, CW_USEDEFAULT, CW_USEDEFAULT,
rect.right - rect.left, rect.bottom - rect.top, nullptr, nullptr, instance,
this);
const int window_width = rect.right - rect.left;
const int window_height = rect.bottom - rect.top;
const int work_width = work.right - work.left;
const int work_height = work.bottom - work.top;
const int x = work.left + (std::max)(0, (work_width - window_width) / 2);
const int y = work.top + (std::max)(0, (work_height - window_height) / 2);
HWND hwnd = CreateWindowExW(0, kWindowClass, kWindowTitle, style, x, y,
window_width, window_height, nullptr, nullptr,
instance, this);
if (hwnd == nullptr) {
provider_ = nullptr;
return false;
}
hwnd_ = hwnd;
aspect_ratio_ = 0.0;
applied_aspect_ = 0.0;
aspect_ratio_ = aspect;
// 预先记下已应用的宽高比:首帧与预期一致时就不会再跳一次尺寸。
applied_aspect_ = aspect;
open_.store(true);
ShowWindow(hwnd_, SW_SHOWNORMAL);
UpdateWindow(hwnd_);
@@ -258,15 +307,9 @@ void VideoWindow::ApplyAspectToWindow(double aspect) {
const int work_width = work.right - work.left;
const int work_height = work.bottom - work.top;
int client_width = work_width * 4 / 5;
int client_height = static_cast<int>(client_width / aspect);
const int max_client_height = work_height * 4 / 5;
if (client_height > max_client_height) {
client_height = max_client_height;
client_width = static_cast<int>(client_height * aspect);
}
client_width = (std::max)(client_width, kMinClientWidth);
client_height = (std::max)(client_height, kMinClientHeight);
int client_width = 0;
int client_height = 0;
FitClientSize(aspect, work, &client_width, &client_height);
RECT rect = {0, 0, client_width, client_height};
AdjustWindowRectEx(&rect, GetWindowLongW(hwnd_, GWL_STYLE), FALSE,
+3 -1
View File
@@ -29,7 +29,9 @@ class VideoWindow {
~VideoWindow();
// 创建并显示窗口(已存在则只前置)。必须在平台线程(消息循环所在线程)调用。
bool Open(FrameProvider provider);
// hint_width / hint_height 是被控端屏幕尺寸(可为 0):已知时窗口直接按该比例
// 开成合适大小,不会先弹出一个 16:9 的大窗口再等首帧缩回去。
bool Open(FrameProvider provider, int hint_width, int hint_height);
// 关闭并销毁窗口。必须在平台线程调用。
void Close();
+95 -10
View File
@@ -148,20 +148,90 @@ fn server_handle() -> &'static ServerHandle {
})
}
/// 启动 demo 服务端。重复调用会返回 ERR_ALREADY_RUNNING。
/// 回收上一轮留下的监听线程。
///
/// `stop()` 只是置标志,线程退出有几十毫秒延迟;必须 join 掉才能保证监听端口
/// 真正释放,否则紧接着重新 `start` 会撞上 `Address already in use`,
/// 导致「断开后重连一直连不上」。
fn join_threads(handle: &ServerHandle) {
let threads = handle
.threads
.lock()
.map(|mut guard| std::mem::take(&mut *guard))
.unwrap_or_default();
for thread in threads {
let _ = thread.join();
}
}
/// 关掉当前控制连接,让阻塞在 `read` 上的 `handle_peer` 立刻返回,
/// 从而尽快释放监听端口。
fn shutdown_control_channel(shared: &Shared) {
let stream = shared
.sender
.lock()
.ok()
.and_then(|mut guard| guard.take())
.map(|sender| sender.stream);
if let Some(stream) = stream {
if let Ok(stream) = stream.lock() {
let _ = stream.shutdown(std::net::Shutdown::Both);
}
}
}
/// 清掉上一次会话的密钥与控制写端,避免重连后误用旧密钥。
fn reset_session_state(shared: &Shared) {
if let Ok(mut guard) = shared.sender.lock() {
*guard = None;
}
for slot in [&shared.control_key, &shared.video_key, &shared.audio_key] {
if let Ok(mut guard) = slot.lock() {
*guard = None;
}
}
shared.peer_connected.store(false, Ordering::SeqCst);
shared.key_established.store(false, Ordering::SeqCst);
if let Ok(mut ip) = shared.peer_ip.lock() {
ip.clear();
}
}
/// 绑定端口时重试若干次:上一次的监听套接字可能刚关闭、内核尚未回收。
/// 只在「端口被占用」时重试,其它错误(权限、地址不可用)立刻返回。
fn retry_bind<T>(mut attempt_bind: impl FnMut() -> std::io::Result<T>) -> std::io::Result<T> {
let mut last_error = None;
for _ in 0..20 {
match attempt_bind() {
Ok(value) => return Ok(value),
Err(error) => {
if error.kind() != std::io::ErrorKind::AddrInUse {
return Err(error);
}
last_error = Some(error);
thread::sleep(Duration::from_millis(50));
}
}
}
Err(last_error.unwrap_or_else(|| std::io::Error::new(std::io::ErrorKind::Other, "绑定失败")))
}
/// 启动 demo 服务端。已运行或端口已就绪时返回 Ok(幂等)。
pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(), String> {
let handle = server_handle();
if handle.shared.running.load(Ordering::SeqCst) {
return Ok(());
}
handle.shared.running.store(true, Ordering::SeqCst);
// 上一轮的线程可能还没退干净,先 join 再重新绑定端口。
join_threads(handle);
reset_session_state(&handle.shared);
let result = (|| -> Result<(), String> {
let listener = TcpListener::bind(("0.0.0.0", control_port))
let listener = retry_bind(|| TcpListener::bind(("0.0.0.0", control_port)))
.map_err(|error| format!("监听 TCP {} 失败:{}", control_port, error))?;
let video = UdpSocket::bind(("0.0.0.0", video_port))
let video = retry_bind(|| UdpSocket::bind(("0.0.0.0", video_port)))
.map_err(|error| format!("监听 UDP {} 失败:{}", video_port, error))?;
let audio = UdpSocket::bind(("0.0.0.0", audio_port))
let audio = retry_bind(|| UdpSocket::bind(("0.0.0.0", audio_port)))
.map_err(|error| format!("监听 UDP {} 失败:{}", audio_port, error))?;
listener
.set_nonblocking(true)
@@ -173,6 +243,7 @@ pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(),
.set_read_timeout(Some(Duration::from_millis(200)))
.map_err(|error| format!("设置 UDP 超时失败:{}", error))?;
handle.shared.running.store(true, Ordering::SeqCst);
let shared = Arc::clone(&handle.shared);
let tcp = thread::spawn(move || run_tcp(listener, shared));
let video_thread = {
@@ -191,16 +262,22 @@ pub fn start(control_port: u16, video_port: u16, audio_port: u16) -> Result<(),
if result.is_err() {
handle.shared.running.store(false, Ordering::SeqCst);
join_threads(handle);
}
result
}
/// 停止 demo 服务端。
/// 停止 demo 服务端。链路与监听都会断开,可再次 [start]。
pub fn stop() {
let handle = server_handle();
handle.shared.running.store(false, Ordering::SeqCst);
handle.shared.peer_connected.store(false, Ordering::SeqCst);
handle.shared.key_established.store(false, Ordering::SeqCst);
// 先断连接再 join,否则 handle_peer 要等到读超时才退出,端口释放被拖慢。
shutdown_control_channel(&handle.shared);
join_threads(handle);
reset_session_state(&handle.shared);
if let Ok(mut events) = handle.shared.events.lock() {
events.clear();
}
crate::media::stream::clear();
}
@@ -300,7 +377,8 @@ fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
}
shared.peer_connected.store(true, Ordering::Relaxed);
shared.push_event(format!("peer:{}", address));
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
// 握手前给短一点的超时:半开连接不能长时间拖住监听线程(会推迟端口释放)。
let _ = stream.set_read_timeout(Some(Duration::from_millis(1200)));
handle_peer(&mut stream, &shared);
shared.peer_connected.store(false, Ordering::Relaxed);
shared.key_established.store(false, Ordering::Relaxed);
@@ -311,7 +389,12 @@ fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(50));
}
Err(_) => break,
Err(error) => {
// 监听套接字已坏:置回 not running,避免界面显示「已监听」却收不到连接。
shared.push_event(format!("error:listener:{}", error));
shared.running.store(false, Ordering::SeqCst);
break;
}
}
}
}
@@ -361,6 +444,8 @@ fn handle_peer(stream: &mut std::net::TcpStream, shared: &Arc<Shared>) {
return;
}
let _ = stream.flush();
// 握手完成,恢复正常读超时(兼作心跳周期)。
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
let channel = SecureControlChannel::new(control);
if let Ok(write_stream) = stream.try_clone() {
+53
View File
@@ -0,0 +1,53 @@
//! 断开后重连:`stop()` 必须真正释放监听端口,紧接着 `start()` 还能再次接入。
//!
//! 回归用例:之前 `stop()` 只置标志不回收线程,监听套接字要等 `handle_peer`
//! 的读超时才关闭;用户断开后立刻点「连接」会绑定失败(Address already in use),
//! 被控端拨号进来没人接,界面只能报「连接超时」。
use std::io::{Read, Write};
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use ttstdconnect_core::crypto::EphemeralKeyPair;
use ttstdconnect_core::demo_server;
const CONTROL_PORT: u16 = 44201;
const VIDEO_PORT: u16 = 44200;
const AUDIO_PORT: u16 = 44202;
/// 走完 ECDH 握手,返回仍保持连接的控制通道。
fn handshake(port: u16) -> TcpStream {
let pair = EphemeralKeyPair::generate().expect("生成 ECDH 密钥");
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("连接 demo 服务");
stream
.set_read_timeout(Some(Duration::from_secs(3)))
.expect("设置读超时");
stream.write_all(&pair.public_bytes()).expect("发送被控端公钥");
let mut peer_public = [0u8; 65];
stream.read_exact(&mut peer_public).expect("读取主控端公钥");
stream
}
#[test]
fn restart_after_stop_accepts_new_peer() {
demo_server::start(CONTROL_PORT, VIDEO_PORT, AUDIO_PORT).expect("首次启动应成功");
thread::sleep(Duration::from_millis(100));
let first = handshake(CONTROL_PORT);
assert!(demo_server::status().key_established, "首次握手应建立会话密钥");
// 模拟主控端点「断开」:此刻被控端的 TCP 连接还开着,端口仍被占用。
demo_server::stop();
assert!(!demo_server::status().running, "停止后不应显示运行中");
// 立刻重连(用户点「连接」):端口必须已释放,否则后面永远连不上。
demo_server::start(CONTROL_PORT, VIDEO_PORT, AUDIO_PORT).expect("停止后应能立刻重新监听");
thread::sleep(Duration::from_millis(100));
assert!(demo_server::status().running, "重新启动后应处于运行状态");
let second = handshake(CONTROL_PORT);
assert!(demo_server::status().key_established, "重连后应能再次建立会话密钥");
drop(second);
drop(first);
demo_server::stop();
}