Exemple #1
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();
        }