44// If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
55// </copyright>
66
7+ using System . Net ;
8+ using System . Net . Sockets ;
79using DxFeed . Graal . Net . Api ;
810using DxFeed . Graal . Net . Api . Osub ;
911using DxFeed . Graal . Net . Events ;
@@ -17,27 +19,45 @@ namespace DxFeed.Graal.Net.Tests.Api;
1719[ TestFixture ]
1820public class DXEndpointTest
1921{
20- private static readonly Random rnd = new ( ) ;
21-
2222 [ Test ]
2323 public void ConnectToLocalPublisher ( )
2424 {
25- var port = rnd . Next ( 48658 , 49150 ) ;
25+ var port = GetFreePort ( ) ;
2626 var countdownEvent = new CountdownEvent ( 1 ) ;
2727
2828 var pub = Create ( Publisher ) . Connect ( $ ":{ port } ") ;
2929 var feed = Create ( Feed ) ;
30- feed . AddStateChangeListener ( ( _ , newState ) =>
30+ try
3131 {
32- if ( newState == State . Connected )
32+ feed . AddStateChangeListener ( ( _ , newState ) =>
3333 {
34- countdownEvent . Signal ( ) ;
35- }
36- } ) ;
37- feed . Connect ( $ "localhost:{ port } ") ;
38- Assert . That ( countdownEvent . Wait ( new TimeSpan ( 0 , 0 , 3 ) ) , Is . True ) ;
39- pub . Close ( ) ;
40- feed . Close ( ) ;
34+ if ( newState == State . Connected )
35+ {
36+ countdownEvent . Signal ( ) ;
37+ }
38+ } ) ;
39+ feed . Connect ( $ "localhost:{ port } ") ;
40+ Assert . That ( countdownEvent . Wait ( new TimeSpan ( 0 , 0 , 10 ) ) , Is . True ) ;
41+ }
42+ finally
43+ {
44+ pub . Close ( ) ;
45+ feed . Close ( ) ;
46+ }
47+ }
48+
49+ private static int GetFreePort ( )
50+ {
51+ var listener = new TcpListener ( IPAddress . Loopback , 0 ) ;
52+ listener . Start ( ) ;
53+ try
54+ {
55+ return ( ( IPEndPoint ) listener . LocalEndpoint ) . Port ;
56+ }
57+ finally
58+ {
59+ listener . Stop ( ) ;
60+ }
4161 }
4262
4363 [ Test ]
@@ -222,7 +242,7 @@ public void CheckOtcMarketsOrder()
222242 publisher . PublishEvents ( order1 ) ;
223243 publisher . PublishEvents ( order2 ) ;
224244
225- cde . Wait ( 3000 ) ;
245+ Assert . That ( cde . Wait ( TimeSpan . FromSeconds ( 10 ) ) , Is . True , "Expected both published orders to be received" ) ;
226246
227247 foreach ( var eventType in resultList )
228248 {
0 commit comments