Skip to content

Commit 2e7bc32

Browse files
author
Jacques Kang
committed
allow automatically assign listening tcp port
1 parent 5d22380 commit 2e7bc32

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/JKang.IpcServiceFramework.Server/Tcp/TcpIpcServiceEndpoint.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,26 @@ public class TcpIpcServiceEndpoint<TContract> : IpcServiceEndpoint<TContract>
1212
where TContract : class
1313
{
1414
private readonly ILogger<TcpIpcServiceEndpoint<TContract>> _logger;
15+
16+
public int Port { get; private set; }
17+
1518
private readonly TcpListener _listener;
1619

17-
public TcpIpcServiceEndpoint(String name, IServiceProvider serviceProvider, IPAddress ipEndpoint, int port)
20+
public TcpIpcServiceEndpoint(String name, IServiceProvider serviceProvider, IPAddress ipEndpoint, int port = 0)
1821
: base(name, serviceProvider)
1922
{
2023
_listener = new TcpListener(ipEndpoint, port);
2124
_logger = serviceProvider.GetService<ILogger<TcpIpcServiceEndpoint<TContract>>>();
25+
Port = port;
2226
}
2327

2428
public override Task ListenAsync(CancellationToken cancellationToken = default(CancellationToken))
2529
{
2630
_listener.Start();
2731

32+
// If port is dynamically assigned, get the port number after start
33+
Port = ((IPEndPoint)_listener.LocalEndpoint).Port;
34+
2835
cancellationToken.Register(() =>
2936
{
3037
_logger.LogDebug($"Shutting down tcp endpoint '{Name}'...");
@@ -35,7 +42,7 @@ public TcpIpcServiceEndpoint(String name, IServiceProvider serviceProvider, IPAd
3542
{
3643
try
3744
{
38-
_logger.LogDebug($"Listening tcp endpoint '{Name}'...");
45+
_logger.LogDebug($"Listening tcp endpoint '{Name}' on port {Port}...");
3946
while (true)
4047
{
4148
TcpClient client = await _listener.AcceptTcpClientAsync();

src/JKang.IpcServiceFramework.Server/Tcp/TcpIpcServiceHostBuilderExtensions.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ namespace JKang.IpcServiceFramework
55
{
66
public static class TcpIpcServiceHostBuilderExtensions
77
{
8+
public static IpcServiceHostBuilder AddTcpEndpoint<TContract>(this IpcServiceHostBuilder builder,
9+
string name, IPAddress ipEndpoint)
10+
where TContract : class
11+
{
12+
return builder.AddEndpoint(new TcpIpcServiceEndpoint<TContract>(name, builder.ServiceProvider, ipEndpoint));
13+
}
14+
815
public static IpcServiceHostBuilder AddTcpEndpoint<TContract>(this IpcServiceHostBuilder builder,
916
string name, IPAddress ipEndpoint, int port)
1017
where TContract : class

0 commit comments

Comments
 (0)