Files
Rail_Enterprise/client/RailEnterprise.Client/scripts/Net/LocalServerLauncher.cs
T
Alby96andClaude Opus 5.5 c1a0049bcf
CI / Build e test (pull_request) Successful in 1m20s
CI / Immagine Docker (pull_request) Successful in 37s
Infrastruttura: nome «Rail Enterprise», CI e rilasci su Gitea, documentazione
Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*,
variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per
allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos:
CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in
server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly.
Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e
aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 11:14:54 +01:00

95 lines
3.8 KiB
C#

using System.Diagnostics;
using Godot;
namespace RailEnterprise.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 RE_SERVER_PATH, cartella «server» accanto al gioco, build del repository.</summary>
public static string? FindServer()
{
string? env = System.Environment.GetEnvironmentVariable("RE_SERVER_PATH");
if (!string.IsNullOrWhiteSpace(env) && File.Exists(env)) return env;
string exeDir = Path.GetDirectoryName(OS.GetExecutablePath()) ?? ".";
foreach (string name in new[] { "RailEnterprise.Server.exe", "RailEnterprise.Server", "RailEnterprise.Server.dll" })
{
string candidate = Path.Combine(exeDir, "server", name);
if (File.Exists(candidate)) return candidate;
}
// sviluppo: il progetto Godot sta in client/RailEnterprise.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", "RailEnterprise.Server", "bin", config, "net10.0", "RailEnterprise.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;
}
}