Exemple #1
0
 /// <summary>
 ///     Starts the local HTTP server and listen for requests
 /// </summary>
 /// <returns>Task completion object</returns>
 /// <exception cref="InvalidOperationException">
 ///     If failed to find an unused port or prohibited from listening for new
 ///     connections.
 /// </exception>
 public virtual async Task RunServerAsync()
 {
     if (Server != null)
         return;
     const ushort validPortsMin = 1025;
     const ushort validPortsMax = ushort.MaxValue;
     var invalidPorts = new List<ushort>();
     var random = new Random();
     while (invalidPorts.Count < validPortsMax - validPortsMin)
     {
         PortNumber = (ushort) random.Next(validPortsMin, validPortsMax);
         if (invalidPorts.Contains(PortNumber))
             continue;
         try
         {
             Server = new HttpListener(TimeSpan.FromSeconds(30));
             await Server.StartTcpRequestListener(PortNumber);
             Server.HttpRequestObservable.Subscribe(OnHttpRequest);
             using (var testSocket = new TcpSocketClient())
             {
                 var tokenSource = new CancellationTokenSource();
                 var connectOperation = testSocket.ConnectAsync("127.0.0.1", PortNumber.ToString(), false,
                     tokenSource.Token);
                 tokenSource.CancelAfter(TimeSpan.FromSeconds(10));
                 await connectOperation;
                 if (connectOperation.IsFaulted || connectOperation.IsCanceled)
                 {
                     if (connectOperation.Exception != null)
                         throw connectOperation.Exception;
                     throw new InvalidOperationException();
                 }
                 testSocket.Disconnect();
             }
             Protocol = @"http://127.0.0.1:" + PortNumber;
         }
         catch (NotImplementedException)
         {
             Server = null;
             throw;
         }
         catch
         {
             invalidPorts.Add(PortNumber);
             try
             {
                 Server?.StopTcpRequestListener();
             }
             catch
             {
                 // ignored
             }
             Server = null;
             continue;
         }
         return;
     }
     throw new InvalidOperationException(@"There is no free port to bind to on this machine.");
 }
Exemple #2
0
 public void StopListener()
 {
     _httpListener.StopTcpRequestListener();
 }