feat: add ephemeral port (port=0) support

This commit is contained in:
Joseph Doherty
2026-02-22 23:36:01 -05:00
parent 9ae75207fc
commit 38eaaa8b83
2 changed files with 112 additions and 0 deletions

View File

@@ -38,6 +38,7 @@ public sealed class NatsServer : IMessageRouter, ISubListAccess, IDisposable
public string ServerId => _serverInfo.ServerId;
public string ServerName => _serverInfo.ServerName;
public int ClientCount => _clients.Count;
public int Port => _options.Port;
public IEnumerable<NatsClient> GetClients() => _clients.Values;
public Task WaitForReadyAsync() => _listeningStarted.Task;
@@ -82,6 +83,15 @@ public sealed class NatsServer : IMessageRouter, ISubListAccess, IDisposable
_options.Port));
Interlocked.Exchange(ref _startTimeTicks, DateTime.UtcNow.Ticks);
_listener.Listen(128);
// Resolve ephemeral port if port=0
if (_options.Port == 0)
{
var actualPort = ((IPEndPoint)_listener.LocalEndPoint!).Port;
_options.Port = actualPort;
_serverInfo.Port = actualPort;
}
_listeningStarted.TrySetResult();
_logger.LogInformation("Listening on {Host}:{Port}", _options.Host, _options.Port);