mirror of
https://github.com/netchx/netch.git
synced 2026-04-01 19:15:09 +08:00
Refactor Start Port Check Kill Process
This commit is contained in:
@@ -1,11 +1,11 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Netch.Models;
|
||||
using Netch.Servers.Socks5;
|
||||
using Netch.Utils;
|
||||
using static Netch.Utils.PortHelper;
|
||||
|
||||
namespace Netch.Controllers
|
||||
{
|
||||
@@ -105,10 +105,7 @@ namespace Netch.Controllers
|
||||
{
|
||||
controller = ServerHelper.GetUtilByTypeName(server.Type).GetController();
|
||||
|
||||
if (controller is Guard instanceController)
|
||||
Utils.Utils.KillProcessByName(instanceController.MainFile);
|
||||
|
||||
PortCheck(controller.Socks5LocalPort(), "Socks5");
|
||||
TryReleaseTcpPort(controller.Socks5LocalPort(), "Socks5");
|
||||
|
||||
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", controller.Name));
|
||||
|
||||
@@ -133,13 +130,13 @@ namespace Netch.Controllers
|
||||
|
||||
private static void StartMode(Mode mode)
|
||||
{
|
||||
ModeController = ModeHelper.GetModeControllerByType(mode.Type, out var port, out var portName, out var portType);
|
||||
ModeController = ModeHelper.GetModeControllerByType(mode.Type, out var port, out var portName);
|
||||
|
||||
if (ModeController == null)
|
||||
return;
|
||||
|
||||
if (port != null)
|
||||
PortCheck((ushort) port, portName, portType);
|
||||
TryReleaseTcpPort((ushort) port, portName);
|
||||
|
||||
Global.MainForm.StatusText(i18N.TranslateFormat("Starting {0}", ModeController.Name));
|
||||
|
||||
@@ -189,7 +186,7 @@ namespace Netch.Controllers
|
||||
{
|
||||
try
|
||||
{
|
||||
CheckPort(port, portType);
|
||||
PortHelper.CheckPort(port, portType);
|
||||
}
|
||||
catch (PortInUseException)
|
||||
{
|
||||
@@ -200,6 +197,27 @@ namespace Netch.Controllers
|
||||
throw new MessageException(i18N.TranslateFormat("The {0} port is reserved by system.", $"{portName} ({port})"));
|
||||
}
|
||||
}
|
||||
|
||||
public static void TryReleaseTcpPort(ushort port, string portName)
|
||||
{
|
||||
Process? p;
|
||||
if ((p = PortHelper.GetProcessByUsedTcpPort(port)) != null)
|
||||
{
|
||||
if (p.MainModule!.FileName.StartsWith(Global.NetchDir))
|
||||
{
|
||||
p.Kill();
|
||||
p.WaitForExit();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new MessageException(i18N.TranslateFormat("The {0} port is used by {1}.",
|
||||
$"{portName} ({port})",
|
||||
$"({p.Id}){p.MainModule.FileName}"));
|
||||
}
|
||||
}
|
||||
|
||||
PortCheck(port, portName, PortType.TCP);
|
||||
}
|
||||
}
|
||||
|
||||
public class MessageException : Exception
|
||||
|
||||
Reference in New Issue
Block a user