当前位置: 首页>>代码示例>>C#>>正文


C# HttpListener.GetContextAsync方法代码示例

本文整理汇总了C#中System.Net.HttpListener.GetContextAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.GetContextAsync方法的具体用法?C# HttpListener.GetContextAsync怎么用?C# HttpListener.GetContextAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.HttpListener的用法示例。


在下文中一共展示了HttpListener.GetContextAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Listen

        public async Task Listen(string prefix, int maxConcurrentRequests, CancellationToken token)
        {
            HttpListener listener = new HttpListener();
            try
            {
                listener.Prefixes.Add(prefix);
                listener.Start();

                var requests = new HashSet<Task>();
                for (int i = 0; i < maxConcurrentRequests; i++)
                    requests.Add(listener.GetContextAsync());

                while (!token.IsCancellationRequested)
                {
                    Task t = await Task.WhenAny(requests);
                    requests.Remove(t);

                    if (t is Task<HttpListenerContext>)
                    {
                        var context = (t as Task<HttpListenerContext>).Result;
                        requests.Add(ProcessRequestAsync(context));
                        requests.Add(listener.GetContextAsync());
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
开发者ID:gtswindell,项目名称:HTTPListener,代码行数:30,代码来源:Program.cs

示例2: TestAsync

 //static SemaphoreSlim _semaphore = new SemaphoreSlim(100);
 public static async Task<Stopwatch> TestAsync()
 {
     var server = new HttpListener();
     server.Prefixes.Add($"http://{Constants.IpAddress}:{Constants.HttpPort}/");
     server.Start();
     Console.WriteLine("HTTP-сервер готов.");
     var stopwatch = new Stopwatch();
     var contexts = new List<HttpListenerContext>();
     var firstGetContextTask =server.GetContextAsync();
     contexts.Add(await firstGetContextTask);
     Console.WriteLine("Начался HTTP-тест.");
     stopwatch.Start();
     var getContextOtherTasks = Enumerable
         .Repeat((byte)0, Constants.ClientCount - 1)
         .Select(_ =>
         {
             //_semaphore.Wait();
             var contextTask = server.GetContextAsync();
             //_semaphore.Release();
             return contextTask;
         });
     var getContextTasks = new HashSet<Task<HttpListenerContext>>
         (getContextOtherTasks)
     {
         firstGetContextTask
     };
     await ProcessAllAsync(getContextTasks);
     stopwatch.Stop();
     server.Stop();
     return stopwatch;
 }
开发者ID:axxeny,项目名称:ServerEfficiencyTest,代码行数:32,代码来源:HttpTest.cs

示例3: SendEmptyData_Success

        public async Task SendEmptyData_Success()
        {
            using (HttpListener listener = new HttpListener())
            {
                listener.Prefixes.Add(ServerAddress);
                listener.Start();
                Task<HttpListenerContext> serverAccept = listener.GetContextAsync();

                WebSocketClient client = new WebSocketClient();
                Task<WebSocket> clientConnect = client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None);

                HttpListenerContext serverContext = await serverAccept;
                Assert.True(serverContext.Request.IsWebSocketRequest);
                HttpListenerWebSocketContext serverWebSocketContext = await serverContext.AcceptWebSocketAsync(null);

                WebSocket clientSocket = await clientConnect;

                byte[] orriginalData = new byte[0];
                await clientSocket.SendAsync(new ArraySegment<byte>(orriginalData), WebSocketMessageType.Binary, true, CancellationToken.None);

                byte[] serverBuffer = new byte[orriginalData.Length];
                WebSocketReceiveResult result = await serverWebSocketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(serverBuffer), CancellationToken.None);
                Assert.True(result.EndOfMessage);
                Assert.Equal(orriginalData.Length, result.Count);
                Assert.Equal(WebSocketMessageType.Binary, result.MessageType);
                Assert.Equal(orriginalData, serverBuffer);

                clientSocket.Dispose();
            }
        }
开发者ID:nimishbhonsale,项目名称:WebSockets,代码行数:30,代码来源:WebSocketClientTests.cs

示例4: ProcessAsync

		private static async Task ProcessAsync(HttpListener listener)
		{
			while (KeepGoing)
			{
				HttpListenerContext context = await listener.GetContextAsync();
				HandleRequestAsync(context);
			}
		}
开发者ID:eugeneagafonov,项目名称:ConferenceDemos,代码行数:8,代码来源:Program.cs

示例5: HandleRequest

        private async void HandleRequest(HttpListener listener)
        {
            try
            {
                var ctx = await listener.GetContextAsync();
                var req = new Request(ctx.Request, this);

                using (var res = new Response(ctx.Response, this))
                {
                    var key = new RequestMapping(ctx.Request.HttpMethod.ToLower(),
                        req.BaseUrl);

                    if (_responders.ContainsKey(key))
                    {
                        var responder = _responders[key];
                        responder(req, res);
                    }
                    else
                    {
                        res.StatusCode(404);
                    }
                }
            }
            catch (HttpListenerException) {  /*ignore*/ }
            catch (ObjectDisposedException) {  /*ignore*/ }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.GetType().Name);
                Console.Error.WriteLine(ex.Message);
            }
        }
开发者ID:dfcook,项目名称:Express.NET,代码行数:31,代码来源:App.cs

示例6: ReceiveCodeAsync

    public async Task<AuthorizationCodeResponse> ReceiveCodeAsync(string authorizationUrl,
      CancellationToken taskCancellationToken)
    {
      using (var listener = new HttpListener())
      {
        listener.Prefixes.Add(CallbackUrl);
        try
        {
          listener.Start();

          var p = Process.Start(authorizationUrl);


          // Wait to get the authorization code response.
          var context = await listener.GetContextAsync().ConfigureAwait(false);
          var coll = context.Request.QueryString;

          // Write a "close" response.
          using (var writer = new StreamWriter(context.Response.OutputStream))
          {
            writer.WriteLine(ClosePageResponse);
            writer.Flush();
          }
          context.Response.OutputStream.Close();
          // Create a new response URL with a dictionary that contains all the response query parameters.
          return new AuthorizationCodeResponse(coll.AllKeys.ToDictionary(k => k, k => coll[(string) k]));
        }
        finally
        {
          listener.Close();
        }
      }
    }
开发者ID:heartszhang,项目名称:famous,代码行数:33,代码来源:LocalServerCodeReceiver.cs

示例7: HttpListenForOneRequest

        public Task<string> HttpListenForOneRequest()
        {
            return new Task<string>(() =>
            {
                var url = ConfigurationManager.AppSettings["httpListenerUrl"];

                var listener = new HttpListener();
                listener.Prefixes.Add(url);
                listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                listener.TimeoutManager.IdleConnection = TimeSpan.FromMilliseconds(500);
                listener.Start();
                
                HttpListenerContext context = listener.GetContextAsync().Result;

                string requestContent;
                using (var r = new StreamReader(context.Request.InputStream))
                {
                    requestContent = r.ReadToEnd();
                }

                context.Response.StatusCode = 200;
                context.Response.Close();
                listener.Stop();

                return requestContent;
            });
        }
开发者ID:CaseyBurns,项目名称:log4net.ext.JsonHttpAppender,代码行数:27,代码来源:JsonHttpAppenderTests.cs

示例8: BeginListeningAsync

		public async Task BeginListeningAsync (CancellationToken token)
		{
			var listener = new HttpListener ();
			listener.Prefixes.Add (string.Format ("http://*:{0}/", ListenPort));

			try {
				using (token.Register (() => listener.Abort ()))
				using (listener) {
					listener.Start ();
					while (!token.IsCancellationRequested) {
						var context = await listener.GetContextAsync ().ConfigureAwait (false);
						ContextReceived (Catalog, context, token);
					}
				}
			} catch (ObjectDisposedException ex) {
				if (!token.IsCancellationRequested) {
					LoggingService.LogError (ex, "Unexpected ObjectDisposedException in BeginListeningAsync");
					throw;
				}
			} catch (OperationCanceledException) {
				// We cancelled successfully
			} catch (Exception ex) {
				LoggingService.LogError (ex, "Unhandled exception in BeginListeningAsync");
			}
		}
开发者ID:alanmcgovern,项目名称:tunez,代码行数:25,代码来源:RequestHandler.cs

示例9: AuthenticateAsync

        public async Task<ICredential> AuthenticateAsync(Uri requestUri, Uri callbackUri = null)
        {
			var requestUriStrb = new StringBuilder();
			requestUriStrb.Append(requestUri.AbsoluteUri);
			
			if (callbackUri != null)
			{
				requestUriStrb.AppendFormat("&oauth_callback={0}", callbackUri.AbsoluteUri);
			}
			
			var listener = new HttpListener();
			listener.Prefixes.Add(callbackUri.AbsoluteUri);
			listener.Start();
			
			System.Diagnostics.Process.Start(requestUriStrb.ToString());
			
			var ctx = await listener.GetContextAsync();
			
			var token = new Credential(ctx.Request.QueryString.Get("oauth_token"), ctx.Request.QueryString.Get("oauth_verifier"));
			
			// empty response
			// ctx.Response.ContentLength64 = 0;
			// await ctx.Response.OutputStream.WriteAsync(new byte[0], 0, 0);
			ctx.Response.OutputStream.Close();
			
			listener.Stop();
			
			return token;
        }
开发者ID:luzianz,项目名称:TwitterClient,代码行数:29,代码来源:ConsoleWebAuthenticationBroker.cs

示例10: ListenerLoop

 public static async void ListenerLoop(HttpListener listener)
 {
     bool quit;
     do
     {
         quit = await listener.GetContextAsync().ContinueWith(ProcessRequest);
     } while (quit);
 }
开发者ID:BSalita,项目名称:ProxyIntent,代码行数:8,代码来源:Program.cs

示例11: Start

        public IDisposable Start()
        {
            if (inner != null) {
                throw new InvalidOperationException("Already started!");
            }

            var server = new HttpListener();
            server.Prefixes.Add(String.Format("http://+:{0}/", Port));
            server.Start();

            bool shouldStop = false;
            var listener = Task.Run(async () => {
                while (!shouldStop) {
                    var ctx = await server.GetContextAsync();

                    if (ctx.Request.HttpMethod != "GET") {
                        closeResponseWith(ctx, 400, "GETs only");
                        return;
                    }

                    var target = Path.Combine(RootPath, ctx.Request.Url.AbsolutePath.Replace('/', Path.DirectorySeparatorChar).Substring(1));
                    var fi = new FileInfo(target);

                    if (!fi.FullName.StartsWith(RootPath)) {
                        closeResponseWith(ctx, 401, "Not authorized");
                        return;
                    }

                    if (!fi.Exists) {
                        closeResponseWith(ctx, 404, "Not found");
                        return;
                    }

                    try {
                        using (var input = File.OpenRead(target)) {
                            ctx.Response.StatusCode = 200;
                            input.CopyTo(ctx.Response.OutputStream);
                            ctx.Response.Close();
                        }
                    } catch (Exception ex) {
                        closeResponseWith(ctx, 500, ex.ToString());
                    }
                }
            });

            var ret = Disposable.Create(() => {
                shouldStop = true;
                server.Stop();
                listener.Wait(2000);

                inner = null;
            });

            inner = ret;
            return ret;
        }
开发者ID:RxSmart,项目名称:Squirrel.Windows,代码行数:56,代码来源:StaticHttpServer.cs

示例12: Webserver

        static async void Webserver(string[] prefixes)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }

            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");

            var listener = new HttpListener();
            // Add the prefixes.
            foreach (string s in prefixes)
            {
                listener.Prefixes.Add(s);
                Console.WriteLine("Prefix :{0}",s);
            }

            listener.Start();
            Console.WriteLine("{0}=>Listening...", listener);

            while (listener.IsListening)
            {
                // Note: The GetContext method blocks while waiting for a request. 
                var context = await listener.GetContextAsync();
                var request = context.Request;
                var response = context.Response;

                //Console.WriteLine("{0} >> {1} >> {2}", request.RemoteEndPoint, request.HttpMethod, request.RawUrl);
   

                String req = di.FullName + (request.RawUrl).Split(new char[] {'?'},StringSplitOptions.RemoveEmptyEntries).First();


                switch (req)
                {
                    case "/":
                        await ServeRedisAsync(new FileInfo(req + "index.html"), response);
                        break;
                    case "/exit":
                        response.Close();
                        listener.Abort();
                        break;
                    default:
                        await ServeRedisAsync(new FileInfo(req), response);
                        break;
                }
            }
            listener.Stop();
            //Console.WriteLine("REDIS connection {0} opened.", redis.Host);
            redis.Close(true);
            redis.Error -= redis_Error;
            redis.Dispose();
        }
开发者ID:dearing,项目名称:sandbox,代码行数:55,代码来源:Program.cs

示例13: ProcessRequests

        public void ProcessRequests()
        {
            _logger.Info("Web Server started");

            try
            {
                _processRequestTasks = new List<Task>();
                _ws = new WebService(_cfg);

                _logger.Debug("Starting listener");
                _listener = StartListener();

                while (!_shouldStop)
                {
                    var contextTask = _listener.GetContextAsync();
                    while (!contextTask.IsCompleted)
                    {
                        if (_shouldStop)
                            return;

                        CollectFinishedTasks();
                        contextTask.Wait(50);
                    }

                    // Dispatch new processing task
                    var task = Task.Factory.StartNew(() => ProcessRequest(contextTask.Result));
                    _processRequestTasks.Add(task);

                    CollectFinishedTasks();
                    _logger.Debug("Number of running tasks {0}", _processRequestTasks.Count);
                }

                _listener.Stop();
                _listener.Close();
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                _logger.Debug(e.StackTrace);

                if (_listener != null)
                {
                    if (_listener.IsListening)
                        _listener.Stop();

                    _listener.Close();
                }

                _mgr.ReportFailure("WebServer");
            }

            _logger.Info("Web Server stopped");
        }
开发者ID:sqlwristband,项目名称:sqlwristband,代码行数:53,代码来源:WebServer.cs

示例14: BusinessLoop

		public async Task BusinessLoop(CancellationToken token)
		{
			try
			{
				using (HttpListener listener = new HttpListener())
				{
					listener.Prefixes.Add(Config.HTTPSERVER_LAPTOP_PREFIX);
					listener.Start();

					while (!token.IsCancellationRequested && listener.IsListening)
					{
						Task<HttpListenerContext> task = listener.GetContextAsync();

						while (!(task.IsCompleted || task.IsCanceled || task.IsFaulted || token.IsCancellationRequested))
						{
							await Task.WhenAny(task, Task.Delay(Config.HTTPSERVER_TIMEOUT_MS));

							if (task.Status == TaskStatus.RanToCompletion)
							{
								Debug.WriteLine("HTTP Context: Received");
								this.ListenerCallback(task.Result);
								break;
							}
							else if (task.Status == TaskStatus.Canceled || task.Status == TaskStatus.Faulted)
							{
								Debug.WriteLine("HTTP Context: Errored");
								// Error, do nothing
							}
							else
							{
								Debug.WriteLine("HTTP Context: Timedout/Still waiting");
								// Timeout, do nothing
							}
						}
					}
				}
			}
			catch (HttpListenerException e)
			{
				// Bail out - this happens on shutdown
				Debug.WriteLine("HTTP Listener has shutdown: {0}", e.Message);
			}
			catch (TaskCanceledException)
			{
				Debug.WriteLine("HTTP Task Cancelled");
			}
			catch (Exception e)
			{
				Debug.WriteLine("HTTP Unexpected exception: {0}", e.Message);
			}
		}
开发者ID:nusolar,项目名称:sc6-telemetry-code,代码行数:51,代码来源:HttpServerManager.cs

示例15: RunTask

        private async Task RunTask()
        {
            try
            {
                _http = new HttpListener();
                _http.Prefixes.Add(string.Format("http://*:{0}/", _httpPort));
                _http.Start();

                while (!_cts.IsCancellationRequested)
                {
                    try
                    {
                        var context = await _http.GetContextAsync();
                        try
                        {
                            await ProcessRequest(context);
                        }
                        catch (Exception exc)
                        {
                            // request processing exceptions should not break the listen loop
                            Console.WriteLine(exc);
                        }
                    }
                    catch (HttpListenerException)
                    {
                        // A dropped connection or other error in the underlying http conversation
						// Overlook this and try to carry on
                        if (_cts.IsCancellationRequested)
                            break;
                    }
                    catch (TaskCanceledException)
                    {
						// The server listening loop is exitted by raising the cancellation token
                        break;
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc);
                        //TODO: it is be bad to suppress all exceptions here because it could result in a tight loop. Set some sort of failure counter
                    }
                }
            }
            catch (TaskCanceledException)
            {
                // not an error, just a signal to exit - return silently
            }            
        }
开发者ID:DynamicDevices,项目名称:Example-02-WebServer,代码行数:47,代码来源:HttpHandler.cs


注:本文中的System.Net.HttpListener.GetContextAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。