Files
Rail_Enterprise/client/ViaFerrea.Client/scripts/Net/LocalServerLauncher.cs
T
Claude 9a4ada6d9d F3: client Godot minimo, replay dei comandi e collaudi automatici
- Client Godot 4.7 .NET (Godot.NET.Sdk 4.7.2): menu, collegamento, partita
  locale con server figlio; mappa con terreno (fasce, ombreggiatura, rive
  curve con shader, curve di livello), opere, entità, alberi, treni
  interpolati con fumo; strumenti binari con profilo, stazione, deposito,
  segnali, demolizione; pannelli treni, linee, mercato, finanze, schede;
  barra superiore, minimappa, notiziario; italiano e inglese.
- Pilota automatico del client e scripts/client-autopilot.sh: partita locale,
  linea con ponte, treni in moto e schermate (docs/screenshots).
- Registro dei comandi del server (--record) e viaferrea-tools replay.
- PROTOCOL.md normativo, ADR 0009, ARCHITECTURE, STATE e README aggiornati.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
2026-10-02 00:47:42 +00:00

95 lines
3.8 KiB
C#

using System.Diagnostics;
using Godot;
namespace ViaFerrea.Client.Net;
/// <summary>
/// Partita locale: avvia il server come processo figlio con <c>--local --token</c>, legge
/// «LISTENING porta» dallo standard output e lo termina alla chiusura del client.
/// </summary>
public sealed class LocalServerLauncher : IDisposable
{
private Process? _process;
public int Port { get; private set; }
public string Token { get; } = Guid.NewGuid().ToString("N");
/// <summary>Percorso del server: variabile VF_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
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;
}
/// <summary>Avvia il server e attende la porta (al massimo timeout).</summary>
public async Task<int> 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;
}
}