gracefully handle multiple processes

main
Justin Barnett 2025-04-08 09:46:52 -04:00
parent 99ceb49ac3
commit 441c0aac57
1 changed files with 38 additions and 9 deletions

View File

@ -70,12 +70,33 @@ namespace UnityMcpBridge.Editor
return; return;
} }
isRunning = true; // Stop any existing listener to free the port
Stop();
try
{
listener = new TcpListener(IPAddress.Loopback, unityPort); listener = new TcpListener(IPAddress.Loopback, unityPort);
listener.Start(); listener.Start();
isRunning = true;
Debug.Log($"UnityMcpBridge started on port {unityPort}.");
// Assuming ListenerLoop and ProcessCommands are defined elsewhere
Task.Run(ListenerLoop); Task.Run(ListenerLoop);
EditorApplication.update += ProcessCommands; EditorApplication.update += ProcessCommands;
} }
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
Debug.LogError(
$"Port {unityPort} is already in use. Ensure no other instances are running or change the port."
);
}
else
{
Debug.LogError($"Failed to start TCP listener: {ex.Message}");
}
}
}
public static void Stop() public static void Stop()
{ {
@ -84,10 +105,18 @@ namespace UnityMcpBridge.Editor
return; return;
} }
try
{
listener?.Stop();
listener = null;
isRunning = false; isRunning = false;
listener.Stop();
EditorApplication.update -= ProcessCommands; EditorApplication.update -= ProcessCommands;
Debug.Log("UnityMCPBridge stopped."); Debug.Log("UnityMcpBridge stopped.");
}
catch (Exception ex)
{
Debug.LogError($"Error stopping UnityMcpBridge: {ex.Message}");
}
} }
private static async Task ListenerLoop() private static async Task ListenerLoop()