Skip to content

Commit 95d0820

Browse files
committed
Support for setting port 0 on passive tcp/ip channels
1 parent c90ae0a commit 95d0820

5 files changed

Lines changed: 45 additions & 10 deletions

File tree

MessageCommunicator.Tests/MessageChannelTests.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Text;
55
using System.Threading;
66
using System.Threading.Tasks;
7+
using MessageCommunicator.Tests.Util;
78
using Microsoft.VisualStudio.TestTools.UnitTesting;
89

910
namespace MessageCommunicator.Tests
@@ -14,20 +15,22 @@ public class MessageChannelTests
1415
[TestMethod]
1516
public async Task Check_SimpleTcpIPConnection()
1617
{
18+
var testingPort = TestUtility.GetFreeTcpPort();
19+
1720
var receiveTaskOnPassiveChannel = new TaskCompletionSource<string>();
1821
var receiveTaskOnActiveChannel = new TaskCompletionSource<string>();
1922

2023
// Define channels
2124
var passiveChannel = new MessageChannel(
22-
new TcpPassiveByteStreamHandlerSettings(IPAddress.Loopback, 40000),
25+
new TcpPassiveByteStreamHandlerSettings(IPAddress.Loopback, testingPort),
2326
new DefaultMessageRecognizerSettings(Encoding.UTF8),
2427
(msg) =>
2528
{
2629
receiveTaskOnPassiveChannel.SetResult(msg.ToString());
2730
msg.ReturnToPool();
2831
});
2932
var activeChannel = new MessageChannel(
30-
new TcpActiveByteStreamHandlerSettings("127.0.0.1", 40000),
33+
new TcpActiveByteStreamHandlerSettings("127.0.0.1", testingPort),
3134
new DefaultMessageRecognizerSettings(Encoding.UTF8),
3235
(msg) =>
3336
{

MessageCommunicator.Tests/MessageCommunicator.Tests.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<TargetFramework>netcoreapp3.1</TargetFramework>
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Net;
4+
using System.Net.Sockets;
5+
using System.Runtime.InteropServices.ComTypes;
6+
using System.Text;
7+
8+
namespace MessageCommunicator.Tests.Util
9+
{
10+
internal static class TestUtility
11+
{
12+
public static ushort GetFreeTcpPort()
13+
{
14+
// Simple method do find a free port
15+
// see https://stackoverflow.com/questions/138043/find-the-next-tcp-port-in-net
16+
17+
var dummyListener = new TcpListener(IPAddress.Loopback, 0);
18+
19+
dummyListener.Start();
20+
var port = (ushort)((IPEndPoint)dummyListener.LocalEndpoint).Port;
21+
dummyListener.Stop();
22+
23+
return port;
24+
}
25+
}
26+
}

MessageCommunicator/MessageChannel.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,16 @@ public class MessageChannel
2020

2121
public string RemoteEndpointDescription => _byteStreamHandler.RemoteEndpointDescription;
2222

23-
public IMessageReceiveHandler ReceiveHandler { get; }
23+
public IMessageReceiveHandler? ReceiveHandler
24+
{
25+
get => _messageRecognizer.ReceiveHandler;
26+
set => _messageRecognizer.ReceiveHandler = value;
27+
}
2428

2529
public MessageChannel(
2630
ByteStreamHandlerSettings byteStreamHandlerSettings,
2731
MessageRecognizerSettings messageRecognizerSettings,
28-
IMessageReceiveHandler receiveHandler,
32+
IMessageReceiveHandler? receiveHandler = null,
2933
IMessageCommunicatorLogger? logger = null)
3034
{
3135
_byteStreamHandler = byteStreamHandlerSettings.CreateByteStreamHandler();

MessageCommunicator/_ByteStreamHandler/_Tcp/TcpPassiveByteStreamHandler.cs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ private async void RunConnectionMainLoop(int loopId)
122122
CancellationTokenSource? lastCancelTokenSource = null;
123123
TcpListener? tcpListener = null;
124124
var reconnectErrorCount = 0;
125+
var currentListenerPort = this.ListeningPort;
125126
while(loopId == _runningLoopCounter)
126127
{
127128
if (tcpListener == null)
@@ -136,6 +137,7 @@ private async void RunConnectionMainLoop(int loopId)
136137
}
137138
tcpListener = new TcpListener(this.ListeningIPAddress, this.ListeningPort);
138139
tcpListener.Start();
140+
currentListenerPort = (ushort)((IPEndPoint)tcpListener.LocalEndpoint).Port;
139141

140142
reconnectErrorCount = 0;
141143
_currentListener = tcpListener;
@@ -144,7 +146,7 @@ private async void RunConnectionMainLoop(int loopId)
144146
{
145147
this.Log(
146148
LoggingMessageType.Info,
147-
StringBuffer.Format("TcpListener created for port {0}", this.ListeningPort));
149+
StringBuffer.Format("TcpListener created for port {0}", currentListenerPort));
148150
}
149151
}
150152
catch (Exception ex)
@@ -153,7 +155,7 @@ private async void RunConnectionMainLoop(int loopId)
153155
{
154156
this.Log(
155157
LoggingMessageType.Error,
156-
StringBuffer.Format("Error while creating TcpListener for port {0}: {1}", this.ListeningPort, ex.Message),
158+
StringBuffer.Format("Error while creating TcpListener for port {0}: {1}", currentListenerPort, ex.Message),
157159
exception: ex);
158160
}
159161

@@ -180,7 +182,7 @@ await this.WaitByReconnectWaitTimeAsync(reconnectErrorCount)
180182
this.Log(
181183
LoggingMessageType.Info,
182184
StringBuffer.Format("Listening for incoming connections on port {0}...",
183-
this.ListeningPort));
185+
currentListenerPort));
184186
}
185187

186188
actTcpClient = await tcpListener.AcceptTcpClientAsync()
@@ -194,7 +196,7 @@ await this.WaitByReconnectWaitTimeAsync(reconnectErrorCount)
194196
LoggingMessageType.Info,
195197
StringBuffer.Format(
196198
"Got new connection on listening port {0}. Connection established between {1} and {2}",
197-
this.ListeningPort, actLocalEndPoint.ToString(), actPartnerEndPoint.ToString()));
199+
currentListenerPort, actLocalEndPoint.ToString(), actPartnerEndPoint.ToString()));
198200
}
199201
}
200202
catch (ObjectDisposedException)
@@ -210,7 +212,7 @@ await this.WaitByReconnectWaitTimeAsync(reconnectErrorCount)
210212
{
211213
this.Log(
212214
LoggingMessageType.Error,
213-
StringBuffer.Format("Error while listening for incoming connections on port {0}: {1}", this.ListeningPort, ex.Message),
215+
StringBuffer.Format("Error while listening for incoming connections on port {0}: {1}", currentListenerPort, ex.Message),
214216
exception: ex);
215217
}
216218

0 commit comments

Comments
 (0)