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
        private async Task StartListener()
        {
            var comm        = new CommunicationsInterface();
            var allComms    = comm.GetAllInterfaces();
            var networkComm = allComms.FirstOrDefault(x => x.GatewayAddress != null);

            var httpListener = new HttpListener(timeout: TimeSpan.FromSeconds(3));
            await httpListener.StartTcpRequestListener(port : 8000, communicationInterface : networkComm);

            await httpListener.StartTcpResponseListener(port : 8001, communicationInterface : networkComm);

            await httpListener.StartUdpMulticastListener(ipAddr : "239.255.255.250", port : 1900, communicationInterface : networkComm);


            var observeHttpRequests = httpListener
                                      .HttpRequestObservable
                                      // Must observe on Dispatcher for XAML to work
                                      .ObserveOnDispatcher().Subscribe(async
                                                                       request =>
            {
                if (!request.IsUnableToParseHttp)
                {
                    Method.Text = request?.Method ?? "N/A";
                    Path.Text   = request?.Path ?? "N/A";
                    if (request.RequestType == RequestType.TCP)
                    {
                        var response = new HttpReponse
                        {
                            StatusCode     = (int)HttpStatusCode.OK,
                            ResponseReason = HttpStatusCode.OK.ToString(),
                            Headers        = new Dictionary <string, string>
                            {
                                { "Date", DateTime.UtcNow.ToString("r") },
                                { "Content-Type", "text/html; charset=UTF-8" },
                            },
                            Body = new MemoryStream(Encoding.UTF8.GetBytes($"<html>\r\n<body>\r\n<h1>Hello, World! {DateTime.Now}</h1>\r\n</body>\r\n</html>"))
                        };

                        await httpListener.HttpReponse(request, response).ConfigureAwait(false);
                    }
                }
                else
                {
                    Method.Text = "Unable to parse request";
                }
            },
                                                                       // Exception
                                                                       ex =>
            {
            });

            // Remember to dispose of subscriber when done
            //observeHttpRequests.Dispose();
        }
Exemple #3
0
        public async Task StartListener()
        {
            await _httpListener.StartTcpRequestListener(Port).ConfigureAwait(false);

            _httpListener.HttpRequestObservable.Subscribe(OnHttpRequest, OnHttpError);
        }