using System.Diagnostics; using Godot; namespace ViaFerrea.Client.Net; /// /// Partita locale: avvia il server come processo figlio con --local --token, legge /// «LISTENING porta» dallo standard output e lo termina alla chiusura del client. /// public sealed class LocalServerLauncher : IDisposable { private Process? _process; public int Port { get; private set; } public string Token { get; } = Guid.NewGuid().ToString("N"); /// Percorso del server: variabile VF_SERVER_PATH, cartella «server» accanto al gioco, build del repository. public static string? FindServer() { string? env = System.Environment.GetEnvironmentVariable("VF_SERVER_PATH"); if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env; string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? "."; foreach (string name in new[] { "ViaFerrea.Server.exe", "ViaFerrea.Server", "ViaFerrea.Server.dll" }) { string candidate = Path.Combine(exeDir, "server", name); if (File.Exists(candidate)) return candidate; } // sviluppo: il progetto Godot sta in client/ViaFerrea.Client, il server in src/ string project = ProjectSettings.GlobalizePath("res://"); foreach (string config in new[] { "Release", "Debug" }) { string candidate = Path.GetFullPath(Path.Combine(project, "..", "..", "src", "ViaFerrea.Server", "bin", config, "net10.0", "ViaFerrea.Server.dll")); if (File.Exists(candidate)) return candidate; } return null; } /// Avvia il server e attende la porta (al massimo timeout). public async Task StartAsync(string serverPath, string dataDir, TimeSpan timeout) { bool dll = serverPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase); var info = new ProcessStartInfo { FileName = dll ? "dotnet" : serverPath, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(serverPath) ?? ".", }; if (dll) info.ArgumentList.Add(serverPath); info.ArgumentList.Add("--local"); info.ArgumentList.Add("--token"); info.ArgumentList.Add(Token); info.ArgumentList.Add("--data"); info.ArgumentList.Add(dataDir); _process = Process.Start(info) ?? throw new InvalidOperationException("Server non avviato"); _process.ErrorDataReceived += (_, e) => { if (e.Data is not null) GD.PrintErr("[server] " + e.Data); }; _process.BeginErrorReadLine(); using var cts = new CancellationTokenSource(timeout); while (!cts.IsCancellationRequested) { string? line = await _process.StandardOutput.ReadLineAsync(cts.Token); if (line is null) break; if (line.StartsWith("LISTENING ", StringComparison.Ordinal) && int.TryParse(line.AsSpan(10), out int port)) { Port = port; // il resto dell'output (log JSON) si scarta per non riempire il buffer _ = Task.Run(async () => { while (await _process.StandardOutput.ReadLineAsync() is not null) { } }); return port; } } throw new TimeoutException("Il server locale non ha risposto"); } public void Dispose() { try { if (_process is { HasExited: false }) _process.Kill(entireProcessTree: true); } catch (InvalidOperationException) { } _process?.Dispose(); _process = null; } }