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,11 +70,32 @@ namespace UnityMcpBridge.Editor
return; return;
} }
isRunning = true; // Stop any existing listener to free the port
listener = new TcpListener(IPAddress.Loopback, unityPort); Stop();
listener.Start();
Task.Run(ListenerLoop); try
EditorApplication.update += ProcessCommands; {
listener = new TcpListener(IPAddress.Loopback, unityPort);
listener.Start();
isRunning = true;
Debug.Log($"UnityMcpBridge started on port {unityPort}.");
// Assuming ListenerLoop and ProcessCommands are defined elsewhere
Task.Run(ListenerLoop);
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;
} }
isRunning = false; try
listener.Stop(); {
EditorApplication.update -= ProcessCommands; listener?.Stop();
Debug.Log("UnityMCPBridge stopped."); listener = null;
isRunning = false;
EditorApplication.update -= ProcessCommands;
Debug.Log("UnityMcpBridge stopped.");
}
catch (Exception ex)
{
Debug.LogError($"Error stopping UnityMcpBridge: {ex.Message}");
}
} }
private static async Task ListenerLoop() private static async Task ListenerLoop()