Add targeted local port cleanup to desktop workbench
This commit is contained in:
1 parent
51c4f86918
commit
ab9cc8d0a5
8 files changed
+312
-1
No files matched your search
@@ -0,0 +1,152 @@
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ads.Desktop;
|
||||
|
||||
public sealed record PortProcess(int Id, string Name, long StartedUtcTicks);
|
||||
|
||||
public static class LocalPortProcesses
|
||||
{
|
||||
public static void EnsureAvailable(int port)
|
||||
{
|
||||
ValidatePort(port);
|
||||
var probe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, port);
|
||||
try { probe.Server.ExclusiveAddressUse = true; probe.Start(); }
|
||||
catch (System.Net.Sockets.SocketException)
|
||||
{ throw new InvalidOperationException($"本地端口 {port} 仍不可用,可能被自动重启的程序占用或受系统限制。"); }
|
||||
finally { probe.Stop(); }
|
||||
}
|
||||
|
||||
public static IReadOnlyList<PortProcess> Inspect(int port)
|
||||
{
|
||||
ValidatePort(port);
|
||||
var result = new List<PortProcess>();
|
||||
foreach (var id in ListenerIds(port))
|
||||
{
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(id);
|
||||
result.Add(new PortProcess(id, process.ProcessName, process.StartTime.ToUniversalTime().Ticks));
|
||||
}
|
||||
catch (ArgumentException) { /* Listener exited during inspection. */ }
|
||||
catch (Win32Exception)
|
||||
{
|
||||
throw new InvalidOperationException($"无法读取端口 {port} 的进程 PID {id},请检查账户权限。");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static async Task<int> TerminateAsync(int port, IReadOnlyList<PortProcess> inspected, CancellationToken cancellation = default)
|
||||
{
|
||||
ValidatePort(port);
|
||||
if (port == 5037) throw new InvalidOperationException("5037 是 ADB 主服务端口,请选择隧道端口,避免中断其他设备。");
|
||||
var ended = 0;
|
||||
foreach (var owner in inspected)
|
||||
{
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
if (owner.Id <= 4 || owner.Id == Environment.ProcessId)
|
||||
throw new InvalidOperationException($"端口由系统或当前工作台进程占用,不能一键结束 PID {owner.Id}。");
|
||||
// Re-check both port ownership and process creation time immediately
|
||||
// before termination. Never kill by process name or a stale PID alone.
|
||||
if (!ListenerIds(port).Contains(owner.Id)) continue;
|
||||
try
|
||||
{
|
||||
using var process = Process.GetProcessById(owner.Id);
|
||||
if (process.StartTime.ToUniversalTime().Ticks != owner.StartedUtcTicks)
|
||||
throw new InvalidOperationException("进程身份已变化,请重新检查端口后再清理。");
|
||||
if (process.HasExited) continue;
|
||||
process.Kill(entireProcessTree: false);
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||
await process.WaitForExitAsync(timeout.Token);
|
||||
ended++;
|
||||
}
|
||||
catch (ArgumentException) { }
|
||||
catch (Win32Exception)
|
||||
{
|
||||
throw new InvalidOperationException($"无法结束 {owner.Name}(PID {owner.Id}),请检查权限或用管理员身份运行工作台。");
|
||||
}
|
||||
}
|
||||
await WaitUntilAvailableAsync(port, cancellation);
|
||||
return ended;
|
||||
}
|
||||
|
||||
public static async Task WaitUntilAvailableAsync(int port, CancellationToken cancellation = default)
|
||||
{
|
||||
for (var attempt = 0; attempt < 50; attempt++)
|
||||
{
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
if (ListenerIds(port).Count == 0)
|
||||
try { EnsureAvailable(port); return; } catch (InvalidOperationException) { }
|
||||
await Task.Delay(100, cancellation);
|
||||
}
|
||||
throw new InvalidOperationException($"端口 {port} 仍不可用,或占用程序已自动重启,请重新检查。");
|
||||
}
|
||||
|
||||
private static void ValidatePort(int port)
|
||||
{
|
||||
if (port is < 1024 or > 65535) throw new InvalidOperationException("请选择 1024–65535 范围内的本地端口。");
|
||||
}
|
||||
|
||||
private static HashSet<int> ListenerIds(int port)
|
||||
{
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
var ids = WindowsListenerIds(port, 2, 24, 8, 20);
|
||||
ids.UnionWith(WindowsListenerIds(port, 23, 56, 20, 52));
|
||||
return ids;
|
||||
}
|
||||
// macOS provides lsof; Linux can use the same interface when installed.
|
||||
var info = new ProcessStartInfo("lsof") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true };
|
||||
foreach (var argument in new[] { "-nP", $"-iTCP:{port}", "-sTCP:LISTEN", "-t" }) info.ArgumentList.Add(argument);
|
||||
try
|
||||
{
|
||||
using var process = Process.Start(info) ?? throw new InvalidOperationException("无法启动 lsof。");
|
||||
var stdout = process.StandardOutput.ReadToEndAsync();
|
||||
var stderr = process.StandardError.ReadToEndAsync();
|
||||
if (!process.WaitForExit(5000)) { process.Kill(); throw new InvalidOperationException("检查端口超时。"); }
|
||||
var output = stdout.GetAwaiter().GetResult();
|
||||
var error = stderr.GetAwaiter().GetResult();
|
||||
if (process.ExitCode != 0 && (process.ExitCode != 1 || error.Length > 0))
|
||||
throw new InvalidOperationException("lsof 无法检查端口:" + error.Trim());
|
||||
return output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(line => int.TryParse(line.Trim(), out var id) ? id : -1).Where(id => id > 0).ToHashSet();
|
||||
}
|
||||
catch (Win32Exception) { throw new InvalidOperationException("此平台检查端口需要 lsof,请先安装后重试。"); }
|
||||
}
|
||||
|
||||
private static HashSet<int> WindowsListenerIds(int port, int family, int rowSize, int portOffset, int pidOffset)
|
||||
{
|
||||
var result = new HashSet<int>();
|
||||
for (var attempt = 0; attempt < 3; attempt++)
|
||||
{
|
||||
var size = 0;
|
||||
var status = GetExtendedTcpTable(IntPtr.Zero, ref size, true, family, 3, 0);
|
||||
if (status == 0 && size == 0) return result;
|
||||
if (status != 122 && status != 0) throw new Win32Exception((int)status);
|
||||
var table = Marshal.AllocHGlobal(size);
|
||||
try
|
||||
{
|
||||
status = GetExtendedTcpTable(table, ref size, true, family, 3, 0);
|
||||
if (status == 122) continue;
|
||||
if (status != 0) throw new Win32Exception((int)status);
|
||||
var count = Marshal.ReadInt32(table);
|
||||
if (count < 0 || size < 4 || count > (size - 4) / rowSize) throw new InvalidOperationException("系统端口表格式无效。");
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
var row = IntPtr.Add(table, 4 + index * rowSize);
|
||||
var networkPort = (uint)Marshal.ReadInt32(row, portOffset);
|
||||
var localPort = (int)(((networkPort & 0xff) << 8) | ((networkPort >> 8) & 0xff));
|
||||
if (localPort == port) result.Add(Marshal.ReadInt32(row, pidOffset));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
finally { Marshal.FreeHGlobal(table); }
|
||||
}
|
||||
throw new InvalidOperationException("系统端口表正在变化,请重试。");
|
||||
}
|
||||
|
||||
[DllImport("iphlpapi.dll", SetLastError = true)]
|
||||
private static extern uint GetExtendedTcpTable(IntPtr table, ref int size, [MarshalAs(UnmanagedType.Bool)] bool ordered, int family, int tableClass, uint reserved);
|
||||
}
|
||||
@@ -35,6 +35,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
[ObservableProperty] private string relayStatus = "中继尚未检测";
|
||||
[ObservableProperty] private string credentialSource = "未加载客户端凭据";
|
||||
[ObservableProperty] private string toolsStatus = "请检查工具路径";
|
||||
[ObservableProperty] private string portCleanupStatus = "清理会结束所选本地端口的监听进程。";
|
||||
[ObservableProperty] private string model = "—";
|
||||
[ObservableProperty] private string androidVersion = "—";
|
||||
[ObservableProperty] private string apiLevel = "—";
|
||||
@@ -115,6 +116,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
ConnectCommand.NotifyCanExecuteChanged(); DisconnectCommand.NotifyCanExecuteChanged();
|
||||
ReconnectCommand.NotifyCanExecuteChanged(); ReadDeviceInfoCommand.NotifyCanExecuteChanged();
|
||||
StartScrcpyCommand.NotifyCanExecuteChanged(); StopScrcpyCommand.NotifyCanExecuteChanged();
|
||||
ClearPortCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
|
||||
private string Redact(string text)
|
||||
@@ -203,6 +205,38 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
private bool CanReadDeviceInfo() => !IsWorking && Ready;
|
||||
private bool CanStartScrcpy() => !IsWorking && Ready && !ScreenRunning;
|
||||
private bool CanStopScrcpy() => ScreenRunning;
|
||||
private bool CanClearPort() => !IsWorking;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanClearPort))]
|
||||
private Task ClearPortAsync() => Guard(() => Exclusive(async () =>
|
||||
{
|
||||
var selectedPort = Port;
|
||||
if (selectedPort == 5037) throw new InvalidOperationException("不能清理 ADB 主服务端口 5037,请选择隧道端口。");
|
||||
var releasedOwnConnection = HasConnection && endpoint == $"127.0.0.1:{selectedPort}";
|
||||
if (releasedOwnConnection)
|
||||
{
|
||||
Log($"清理端口 {selectedPort}:先断开当前工作台管理的连接。");
|
||||
await DisconnectCoreAsync();
|
||||
}
|
||||
var owners = await Task.Run(() => LocalPortProcesses.Inspect(selectedPort), lifetime.Token);
|
||||
PortCleanupStatus = owners.Count == 0 ? $"端口 {selectedPort} 没有监听进程。" :
|
||||
string.Join(";", owners.Select(owner => $"{owner.Name} · PID {owner.Id} · 端口 {selectedPort}"));
|
||||
foreach (var owner in owners) Log($"清理端口 {selectedPort}:{owner.Name}(PID {owner.Id})。");
|
||||
var ended = await LocalPortProcesses.TerminateAsync(selectedPort, owners, lifetime.Token);
|
||||
try
|
||||
{
|
||||
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
|
||||
await AdbAsync(adb, lifetime.Token, "disconnect", $"127.0.0.1:{selectedPort}");
|
||||
}
|
||||
catch (Exception error) { Log("清除 ADB 端点:" + error.Message); }
|
||||
PortCleanupStatus = releasedOwnConnection && ended == 0
|
||||
? $"本机连接已断开,端口 {selectedPort} 已释放。"
|
||||
: $"端口 {selectedPort} 已释放,结束了 {ended} 个占用进程。";
|
||||
Notice = PortCleanupStatus + " 现在可以重新连接设备。";
|
||||
Log(PortCleanupStatus);
|
||||
if (Token.Length >= 32)
|
||||
try { await RefreshDevicesAsync(announce: false); } catch (Exception error) { Log(error.Message); }
|
||||
}));
|
||||
|
||||
private async Task Exclusive(Func<Task> action)
|
||||
{
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
<TextBlock Text="连接管理" Classes="section"/>
|
||||
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
|
||||
<TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
|
||||
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/></WrapPanel>
|
||||
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
|
||||
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
@@ -96,6 +96,7 @@
|
||||
<Border Classes="card"><StackPanel Spacing="12">
|
||||
<TextBlock Text="本地连接" Classes="section"/>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="本地 ADB 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<WrapPanel><Button Content="清理占用端口" Command="{Binding ClearPortCommand}" ToolTip.Tip="结束当前所选端口的监听进程"/><TextBlock Text="{Binding PortCleanupStatus}" Classes="label" TextWrapping="Wrap" MaxWidth="580" VerticalAlignment="Center"/></WrapPanel>
|
||||
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}"/>
|
||||
<TextBlock Text="配置修改在下一次连接生效。完全退出工作台会停止本机连接;远程守护程序继续运行。" TextWrapping="Wrap" Classes="label"/>
|
||||
<Button Content="保存配置" Command="{Binding SaveCommand}" HorizontalAlignment="Left"/>
|
||||
|
||||
Reference in new issue
Block a user