//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; }
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); } }
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"); } }
private async Task Run() { while (true && !this.shouldStop) { await semaphore.WaitAsync(); try { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed listener.GetContextAsync().ContinueWith(async ctx => { semaphore.Release(); HttpListenerContext context = await ctx; await this.handler.Process(context); }).ConfigureAwait(continueOnCapturedContext: false); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } catch (Exception ex) { this.handler.HandleException(ex); } } }
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; }
private void StartNextRequestAsync() { if (!_listener.IsListening || !CanAcceptMoreRequests) { return; } Interlocked.Increment(ref _currentOutstandingAccepts); try { _listener.GetContextAsync() .Then(_startProcessingRequest, runSynchronously: true) .Catch(_handleAcceptError); } catch (ApplicationException ae) { // These come from the thread pool if HttpListener tries to call BindHandle after the listener has been disposed. HandleAcceptError(ae); } catch (HttpListenerException hle) { // These happen if HttpListener has been disposed HandleAcceptError(hle); } catch (ObjectDisposedException ode) { // These happen if HttpListener has been disposed HandleAcceptError(ode); } }
/// <summary> /// 启动 /// </summary> public async void StartAsync() { var listener = new System.Net.HttpListener(); listener.Prefixes.Add($"http://{_endPoint.ToString()}/GarbageBin/Data/"); // 启动服务器 try { listener.Start(); } catch (Exception ex) { Console.WriteLine($"智慧垃圾桶,启动服务器失败,{ex.ToString()}"); return; } // 消息接收 while (true) { try { var context = await listener.GetContextAsync(); var result = await ReceiveMessage(context); await SendResponse(context, result); } catch (Exception ex) { Console.WriteLine($"智慧垃圾桶,获取请求失败,{ex.ToString()}"); } } }
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(); } }
async Task ProcessContext() { QueueNextRequestPending(); HttpListenerContext nativeContext; try { nativeContext = await _listener.GetContextAsync(); } catch (HttpListenerException) { return; } var ambientContext = new AmbientContext(); var context = new HttpListenerCommunicationContext(this, nativeContext); try { using (new ContextScope(ambientContext)) { var incomingRequestReceivedEventArgs = new IncomingRequestReceivedEventArgs(context); IncomingRequestReceived(this, incomingRequestReceivedEventArgs); await incomingRequestReceivedEventArgs.RunTask; } } finally { using (new ContextScope(ambientContext)) { IncomingRequestProcessed(this, new IncomingRequestProcessedEventArgs(context)); } } }
public static async void ThreadProcAsync() { string uriPrefix = ConfigurationManager.AppSettings["ListenerPrefix"]; using (System.Net.HttpListener listener = new System.Net.HttpListener()) { listener.Prefixes.Add(uriPrefix); listener.IgnoreWriteExceptions = true; // For the sake of the development convenience, this code opens default web browser // with this server url when project is started in the debug mode as a console app. #if DEBUG if (!IsServiceMode) { System.Diagnostics.Process.Start(uriPrefix.Replace("+", "localhost"), null); } #endif listener.Start(); Console.WriteLine("Start listening on " + uriPrefix); Console.WriteLine("Press Control-C to stop listener..."); while (Listening) { HttpListenerContext context = await listener.GetContextAsync(); #pragma warning disable 4014 Task.Factory.StartNew(() => ProcessRequestAsync(listener, context)); #pragma warning restore 4014 } } }
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(); } } }
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; }); }
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); } }
public async void Start() { _listener.Prefixes.Add(_prefix); _listener.Start(); Console.WriteLine($"Started listening on {_prefix}"); while (_listener.IsListening) { try { var context = await _listener.GetContextAsync(); var stopwatch = new Stopwatch(); Console.WriteLine($"Request starting HTTP/{context.Request.ProtocolVersion} {context.Request.HttpMethod} {context.Request.Url}"); stopwatch.Start(); await ProcessRequest(context); stopwatch.Stop(); Console.WriteLine($"Request finished in {stopwatch.Elapsed.TotalMilliseconds:0.####}ms {context.Response.StatusCode} {context.Response.ContentType}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
private async Task ListenAsync() { while (mHttpListener.IsListening) { HttpListenerContext context = await mHttpListener.GetContextAsync().ConfigureAwait(false); if (!context.Request.IsWebSocketRequest) { OnUnknownRequest(context); } else { string subProtocol = GetSubProtocol(context); if (subProtocol == null) { OnUnknownRequest(context); } else { HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(subProtocol); WebSocketData webSocketData = new WebSocketData(webSocketContext, subProtocol); OnNewConnection(webSocketData); } } } }
private static async Task ProcessAsync(HttpListener listener) { while (KeepGoing) { HttpListenerContext context = await listener.GetContextAsync(); HandleRequestAsync(context); } }
public static async void ListenerLoop(HttpListener listener) { bool quit; do { quit = await listener.GetContextAsync().ContinueWith(ProcessRequest); } while (quit); }
public async Task <IRequest> WaitForRequest() { var context = await _httpListener.GetContextAsync(); IRequest request = new Request(context.Request); _contexts[request] = context; return(request); }
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; }
public async Task <FrameStream> ReceiveAsync(CancellationToken token) { var frames = new FrameStream(); _context = await _httpListener.GetContextAsync(); await _context.Request.InputStream.CopyToAsync(frames); return(frames); }
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(); }
/// <summary> /// Start the http listener. /// </summary> public async void Start() { // If not running. if (!_running) { try { // Create a new http listener if (_listener == null) { _listener = new System.Net.HttpListener(); // Add URI prefixes to listen for. foreach (string uri in _uriList) { _listener.Prefixes.Add(uri); } } // Set the Authentication Schemes. _listener.AuthenticationSchemes = _authenticationSchemes; if (_authenticationSchemeSelectorDelegate != null) { _listener.AuthenticationSchemeSelectorDelegate = _authenticationSchemeSelectorDelegate; } // Start the listener _listener.Start(); _running = true; // Keep the service in the running start // listen for in-comming requests. while (_running) { // Wait for the next request. HttpListenerContext listenerContext = await _listener.GetContextAsync(); // Send the http context to the handler. if (listenerContext != null) { AsynchronousListener(listenerContext); } } } catch (Exception) { if (_listener != null) { _listener.Close(); } throw; } } }
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"); }
private void AddConnectionForListener() { var taskForListening = _listener.GetContextAsync(); taskForListening.ContinueWith(x => { ProcessRequest(x); _connections.Remove(x); AddConnectionForListener(); }); _connections.Add(taskForListening); }
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); } }
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 } }
private async void ProcessRequestsAsync() { // 为什么需要这个while循环?? // 确保原线程继续使用,用OffloadStartNextRequest()开多个线程,CanAcceptMoreRequests|_currentOutstandingAccepts为最大线程上限 // 一开始只有一个线程,每多请求一次,多一个线程 while (_listener.IsListening && CanAcceptMoreRequests) { Interlocked.Increment(ref _currentOutstandingAccepts); HttpListenerContext context; try { context = await _listener.GetContextAsync(); } catch (ApplicationException ae) { // These come from the thread pool if HttpListener tries to call BindHandle after the listener has been disposed. Interlocked.Decrement(ref _currentOutstandingAccepts); LogHelper.LogException(_logger, "Accept", ae); return; } catch (HttpListenerException hle) { // These happen if HttpListener has been disposed Interlocked.Decrement(ref _currentOutstandingAccepts); LogHelper.LogException(_logger, "Accept", hle); return; } catch (ObjectDisposedException ode) { // These happen if HttpListener has been disposed Interlocked.Decrement(ref _currentOutstandingAccepts); LogHelper.LogException(_logger, "Accept", ode); return; } Thread.Sleep(10000); Interlocked.Decrement(ref _currentOutstandingAccepts); Interlocked.Increment(ref _currentOutstandingRequests); OffloadStartNextRequest(); // This needs to be separate from ProcessRequestsAsync so that async/await will clean up the execution context. // This prevents changes to Thread.CurrentPrincipal from leaking across requests. await ProcessRequestAsync(context); } }
private async void StartListening(HttpListener listener) { while (listener.IsListening) { try { var context = await listener.GetContextAsync(); var request = context.Request; string username = Regex.Match(request.RawUrl, "steam/(.*)/stop$").Groups[1].Value; string responseString = ""; if (request.RawUrl.EndsWith("/stop")) { var proc = GetProcessInfoByWMI("steam"); if (proc == null) { responseString = "steam not running"; } else { if (username.ToLower() != proc.Username.ToLower()) { StopProcess(proc.ProcessId); responseString = "steam stopped, pid: " + proc.ProcessId.ToString(); } else { responseString = "already running steam process on user: " + proc.Username; } } } var response = context.Response; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; using (System.IO.Stream output = response.OutputStream) { output.Write(buffer, 0, buffer.Length); } } catch (Exception) { } } }
public async Task Start() { _cts = new CancellationTokenSource(); _httpListener = new System.Net.HttpListener(); _httpListener.Prefixes.Add("http://localhost:8181/incoming/"); _httpListener.Start(); Console.WriteLine("Listening at {0}", _httpListener.Prefixes.First()); while (!_cts.IsCancellationRequested) { var context = await _httpListener.GetContextAsync(); var handlerTask = HandleNewConnection(context); _listeners.TryAdd(handlerTask); #pragma warning disable 4014 handlerTask.ContinueWith(t => _listeners.TryRemove(handlerTask)); #pragma warning restore 4014 } }
static HttpListener staticHttpListener; // fugly: is there any way to avoid this? This stems from GetContextAsync() only registering a callback for a single request, whereas a nodejs server registers a callback for a whole series of requests. #endregion Fields #region Methods public static void run() { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:9080/"); listener.Start(); Console.WriteLine("Listening..."); // This listener.BeginGetContext only registers a callback for a single HTTP request. staticHttpListener = listener; // fugly: just so that the processGetContextResult() handler can trigger another GetContextAsync call. listener.GetContextAsync().ContinueWith(processGetContextResult); // this GetContextAsync() only registered a callback, if we don't prevent the process // from terminating explicitly here it will exit right away. // Isnt it kinda ugly that we have to WaitOne() here? Would be nice to make a call to pump // the message queue? shutdownRequest.WaitOne(); listener.Stop(); }
async Task AcceptRequests() { while (_listener.IsListening) { try { var context = await _listener.GetContextAsync(); #pragma warning disable 4014 Task.Run(async() => await ProcessContext(context)); #pragma warning restore 4014 } catch (HttpListenerException) { return; } } }
public async Task Listen(ushort port) { try { using (System.Net.HttpListener listener = new System.Net.HttpListener()) { listener.Prefixes.Add($"http://localhost:{port.ToString()}/Device/Data/"); listener.Start(); Console.WriteLine("开始监听"); while (true) { try { HttpListenerContext context = await listener.GetContextAsync();//阻塞 HttpListenerRequest request = context.Request; string postData = new StreamReader(request.InputStream).ReadToEnd(); Console.WriteLine("收到请求:" + postData); HttpListenerResponse response = context.Response;//响应 string responseBody = "OK"; response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody); response.StatusCode = 200; //输出响应内容 Stream output = response.OutputStream; using (StreamWriter sw = new StreamWriter(output)) { sw.Write(responseBody); } Console.WriteLine("响应结束"); } catch (Exception err) { Console.WriteLine(err.Message); } } } } catch (Exception err) { Console.WriteLine("程序异常,请重新打开程序:" + err.Message); } }
public async Task Connect_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; clientSocket.Dispose(); } }
/// <summary> /// Listens for Http requests asynchronously on the <paramref name="host"/> and directs them to the <paramref name="routes"/>. /// </summary> /// <param name="host"></param> /// <param name="routes">Collection of routes that will serve requests.</param> /// <param name="cancellation">Cancellation token to stop listening (Optional).</param> public static async Task ListenForeverAsync(IReadOnlyCollection<Uri> endpoints, IReadOnlyCollection<Route> routes, CancellationToken cancellation = default(CancellationToken)) { HttpListener listener = new HttpListener(); listener.Prefixes.AddRange(endpoints.Select(ep => ep.ToString())); listener.Start(); List<Task> pendingTasks = new List<Task>(); try { while (true) { cancellation.ThrowIfCancellationRequested(); try { HttpListenerContext context = await listener.GetContextAsync().ConfigureAwait(false); // Begin serving the request. Task serveTask = ServeAsync(context, routes); pendingTasks.Add(serveTask); // Reap completed tasks and propagate exceptions. foreach (Task completedTask in pendingTasks.ConsumeWhere(task => task.IsCompleted)) { await completedTask.ConfigureAwait(false); } await serveTask; } catch (Exception ex) { Debug.WriteLine("HTTPServer caught exception:"); Debug.WriteLine(ex.ToString()); } } } finally { listener.Stop(); await Task.WhenAll(pendingTasks).ConfigureAwait(false); } }
internal static async Task<HttpListenerRequest> ExecuteBrowserWorkflow(string uri, string message, string callBackUri, int timeOut) { Process pWeb = new Process(); HttpListenerRequest result = null; try { using (HttpListener httpListener = new HttpListener()) { Console.WriteLine("Opening browser for a browser based workflow..."); httpListener.Prefixes.Add(callBackUri + "/"); httpListener.Start(); pWeb.StartInfo.FileName = uri; pWeb.StartInfo.WindowStyle = ProcessWindowStyle.Normal; // Start browser pWeb.Start(); // Wait for call back var task = httpListener.GetContextAsync(); if (await Task.WhenAny(task, Task.Delay(timeOut)) == task) { HttpListenerContext hlcContext = task.Result; HttpListenerResponse hlrpResponse = hlcContext.Response; result = hlcContext.Request; // Write the response back to browser string strResponse = String.Format(@"<HTML><HEAD><TITLE>{0}</TITLE></HEAD><BODY>Please close the window.</BODY></HTML>", message); byte[] bBuffer = System.Text.Encoding.UTF8.GetBytes(strResponse); hlrpResponse.ContentLength64 = bBuffer.Length; System.IO.Stream smOutput = hlrpResponse.OutputStream; smOutput.Write(bBuffer, 0, bBuffer.Length); smOutput.Close(); httpListener.Stop(); } else { Console.WriteLine(@"Operation canceled - timeout"); } } } finally { pWeb.Close(); } return result; }
private static async Task httpServer() { CoopScheduler.AddTask(async () => { while (true) { await Task.Delay(1000); Console.WriteLine("waiting"); } }); HttpListener l = new HttpListener(); l.Prefixes.Add("http://+:8080/"); l.Start(); while (true) { var ctx = await l.GetContextAsync(); CoopScheduler.AddTask(() => handleRequest(ctx)); } }
public async Task Start() { using (var listener = new HttpListener()) { listener.Prefixes.Add(string.Format("http://+:{0}/", this.port)); listener.Start(); Console.WriteLine("Listening on port {0}", port); var semaphore = new Semaphore(listenerCount, listenerCount); while (true) { semaphore.WaitOne(); var context = await listener.GetContextAsync(); semaphore.Release(); await Task.Factory.StartNew(() => Handler(context)); } } }
public async static void runAsync() { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:9080/"); listener.Start(); Console.WriteLine("Listening..."); while (true) { HttpListenerContext context = await listener.GetContextAsync(); Console.WriteLine("processing request ..."); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; bool isShutdownRequest = await processRequestAsync(request, response); if (isShutdownRequest) break; Console.WriteLine("done processing request."); } listener.Stop(); }
/// <summary> /// Starting and listening for incoming requests. /// </summary> private async void ThreadProcAsync() { try { using (System.Net.HttpListener listener = new System.Net.HttpListener()) { listener.Prefixes.Add(contextOptions.ListenerPrefix); // We do not use AuthenticationSchemes.Digest here because OPTIONS request must be processed without authentication. // Instead this sample provides its own Digest authentication implementation. listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; listener.IgnoreWriteExceptions = true; listener.Start(); string listenerPrefix = contextOptions.ListenerPrefix.Replace("+", LocalIPAddress().ToString()); string startMessage = $"Started listening on {contextOptions.ListenerPrefix}.\n\n" + $"To access your files go to {listenerPrefix} in a web browser. Or just connect to the above address using WebDAV client."; logger.LogDebug(startMessage); logMethod.LogOutput(startMessage); while (Listening) { HttpListenerContext context = await listener.GetContextAsync(); #pragma warning disable 4014 Task.Factory.StartNew(() => ProcessRequestAsync(listener, context)); #pragma warning restore 4014 } } } catch (HttpListenerException ex) when(ex.ErrorCode == 5) { logger.LogError("Access is denied, try to run with administrative privileges.", null); } catch (Exception ex) { logger.LogError(ex.Message, ex); } }
public async void Start() { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8181/"); listener.Start(); while (true) { try { var context = await listener.GetContextAsync(); messageQueue.Enqueue(ProcessJsonRequest(context)); context.Response.StatusCode = 200; context.Response.Close(); } catch { return; } } }
//### Starting the server // Using HttpListener is reasonably straightforward. Start the listener and run a loop that receives and processes incoming WebSocket connections. // Each iteration of the loop "asynchronously waits" for the next incoming request using the `GetContextAsync` extension method (defined below). // If the request is for a WebSocket connection then pass it on to `ProcessRequest` - otherwise set the status code to 400 (bad request). public async void Start(string listenerPrefix) { HttpListener listener = new HttpListener(); listener.Prefixes.Add(listenerPrefix); listener.Start(); Console.WriteLine("Listening..."); while (true) { HttpListenerContext listenerContext = await listener.GetContextAsync(); if (listenerContext.Request.IsWebSocketRequest) { ProcessRequest(listenerContext); } else { listenerContext.Response.StatusCode = 400; listenerContext.Response.Close(); } } }
public HttpServer(string url) { if (!HttpListener.IsSupported) { Console.WriteLine("Not Supported!"); return; } listener = new HttpListener(); listener.Prefixes.Add(url); try { listener.Start(); } catch (Exception e) { Console.WriteLine(e.Message); return; } SessionMap = new Dictionary<string, SearchSession>(); listener.GetContextAsync(); //listener.BeginGetContext(new AsyncCallback(HttpRequestCallback), this); }
public async void Start(string httpListenerPrefix) { HttpListener httpListener = new HttpListener(); httpListener.Prefixes.Add(httpListenerPrefix); httpListener.Start(); Console.WriteLine("Listening..."); webSocketDictionary = new WebSocketDictionary(); while(true) { HttpListenerContext httpListenerContext = await httpListener.GetContextAsync(); if (httpListenerContext.Request.IsWebSocketRequest) { ProcessRequest(httpListenerContext); } else { httpListenerContext.Response.StatusCode = 400; httpListenerContext.Response.Close(); } } }
public async void Start() { listener = new HttpListener(); listener.Prefixes.Add(url); listener.Start(); while (true) { Console.WriteLine("waiting...."); HttpListenerContext context = await listener.GetContextAsync(); // Respond to the request: string msg = "You asked for: " + context.Request.RawUrl; context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(content); context.Response.StatusCode = (int)HttpStatusCode.OK; using (var stream = context.Response.OutputStream) { using (var writer = new StreamWriter(stream)) { await writer.WriteAsync(content); } } Console.WriteLine("message sent...."); } }
private static async void ListeningLoop() { var listener = new HttpListener(); listener.Prefixes.Add("http://+:4444/"); listener.IgnoreWriteExceptions = true; listener.Start(); while (true) { var context = await listener.GetContextAsync(); try { if (context.Request.Url.LocalPath == "/screen.png") { var screenshot = Shooter.MakeScreenShot(Screen.PrimaryScreen); screenshot.Save(context.Response.OutputStream, ImageFormat.Png); } } finally { context.Response.Close(); } } }
public async void Start(string prefix) { var listener = new HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); Console.WriteLine("Listening..."); while (true) { var context = await listener.GetContextAsync(); Console.WriteLine("Got request."); if (context.Request.IsWebSocketRequest) { HandleRequest(context); } else { context.Response.StatusCode = 400; context.Response.Close(); } } }
public async Task <string> InitiateTokenRetrieval() { try { string state = RandomDataBase64Url(32); string redirectURI = ""; var http = new System.Net.HttpListener(); foreach (var i in new int[] { 17236, 17284, 17287, 17291, 17296 }) { try { redirectURI = string.Format("http://localhost:{0}/", i); http.Prefixes.Add(redirectURI); http.Start(); break; } catch { http = new System.Net.HttpListener(); } } // Creates the OAuth 2.0 authorization request. string authorizationRequest = string.Format("{0}?response_type=code&scope=remote_control:all&client_id={1}&state={2}&redirect_uri={3}", _lIFXAuthorizationEndpoint, _options.LightSettings.LIFX.LIFXClientId, state, HttpUtility.UrlEncode(redirectURI) ); Helpers.OpenBrowser(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync().ConfigureAwait(true); //Sends an HTTP response to the browser. var response = context.Response; string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://lifx.com'></head><body>Please return to the app.</body></html>"); var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); Debug.WriteLine("HTTP server stopped."); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { return(""); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { return(""); } // extracts the code var code = context.Request.QueryString.Get("code") ?? ""; var incoming_state = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incoming_state != state) { return(""); } // Starts the code exchange at the Token Endpoint. return(await PerformCodeExchange(code).ConfigureAwait(true)); } catch (Exception e) { _logger.LogError("Error retrieving LIFX Token", e); throw; } }
private static async Task <AuthResult> PollinationSignInAsync(bool devEnv = false) { if (!HttpListener.IsSupported) { Helper.Logger.Error($"PollinationSignInAsync: HttpListener is not supported on this system"); throw new ArgumentException("PollinationSignIn is not supported on this system"); } var redirectUrl = "http://localhost:8645/"; var loginUrl = devEnv ? LoginURL_Dev : LoginURL; var listener = new System.Net.HttpListener(); try { listener.Prefixes.Add(redirectUrl); listener.Start(); //listener.TimeoutManager.IdleConnection = TimeSpan.FromSeconds(30); //listener.TimeoutManager.HeaderWait = TimeSpan.FromSeconds(30); } catch (HttpListenerException e) { //it is already listening the port, but users didn't login if (e.ErrorCode == 183) { Console.WriteLine(e.Message); Helper.Logger.Warning($"PollinationSignInAsync: it is still waiting for users to login from last time.\n{e.Message}"); } else { Helper.Logger.Error($"PollinationSignInAsync: Failed to start the listener.\n{e.Message}"); throw e; } } var psi = new System.Diagnostics.ProcessStartInfo { FileName = loginUrl, UseShellExecute = true }; System.Diagnostics.Process.Start(psi); Helper.Logger.Information($"PollinationSignInAsync: login from {loginUrl}"); // wait for the authorization response. var context = await listener.GetContextAsync(); var request = context.Request; var response = context.Response; var returnUrl = request.RawUrl.Contains("?token=") ? request.RawUrl : request.UrlReferrer?.PathAndQuery; if (string.IsNullOrEmpty(returnUrl)) { Helper.Logger.Error($"PollinationSignInAsync: Failed to authorize the login: \n{request.RawUrl}"); throw new ArgumentException($"Failed to authorize the login: \n{request.RawUrl}"); } //sends an HTTP response to the browser. string responseString = string.Format("<html><head></head><body style=\"text-align: center; font-family: Lato, Helvetica, Arial, sans-serif\"><img src=\"https://app.pollination.cloud/logo.svg\"><h1>Authorization was successful!</h1><p>You can close this browser window.</p></body></html>"); var buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; await responseOutput.WriteAsync(buffer, 0, buffer.Length); await Task.Delay(1000); responseOutput.Flush(); responseOutput.Close(); listener.Stop(); Helper.Logger.Information($"PollinationSignInAsync: closing the listener"); return(AuthResult.From(request.QueryString)); }
public async Task <string> InitiateTokenRetrieval() { string state = RandomDataBase64Url(32); string redirectURI = ""; var http = new System.Net.HttpListener(); foreach (var i in new int[] { 17236, 17284, 17287, 17291, 17296 }) { try { redirectURI = string.Format("http://localhost:{0}/", i); http.Prefixes.Add(redirectURI); http.Start(); break; } catch (Exception e) { http = new System.Net.HttpListener(); } } var client = new HttpClient(); string json = await client.GetStringAsync("https://presence-light.azurewebsites.net/api/KeyVault?code=0UGo7xdQmumEzoCV8vRNXv6Z8pGxWvtu7b6a0meOtDlQCB43oxIEfw=="); var secretResponse = JsonConvert.DeserializeObject <List <SecretResponse> >(json); _lifxClientId = secretResponse.FirstOrDefault(a => a.Secret == "LIFXClientId").Value; _lifxClientSecret = secretResponse.FirstOrDefault(a => a.Secret == "LIFXClientSecret").Value; // Creates the OAuth 2.0 authorization request. string authorizationRequest = string.Format("{0}?response_type=code&scope=remote_control:all&client_id={1}&state={2}&redirect_uri={3}", _lIFXAuthorizationEndpoint, _lifxClientId, state, HttpUtility.UrlEncode(redirectURI) ); Helpers.OpenBrowser(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); //Sends an HTTP response to the browser. var response = context.Response; string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://lifx.com'></head><body>Please return to the app.</body></html>"); var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); Debug.WriteLine("HTTP server stopped."); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { return(""); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { return(""); } // extracts the code var code = context.Request.QueryString.Get("code") ?? ""; var incoming_state = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incoming_state != state) { return(""); } // Starts the code exchange at the Token Endpoint. return(await PerformCodeExchange(code)); }
public static async Task <string> SignIn() { // create a redirect URI using an available port on the loopback address. //string redirectUri = string.Format("https://app.pollination.cloud/callback"); string redirectUri = string.Format("http://localhost:3000/"); Console.WriteLine("redirect URI: " + redirectUri); Console.WriteLine("-----------------------------------"); // create an HttpListener to listen for requests on that redirect URI. var listener = new System.Net.HttpListener(); listener.Prefixes.Add(redirectUri); Console.WriteLine("Listening.."); listener.Start(); var verifier = GenVerifier(); var codeChallenge = GenCodeChallenge(verifier); //var verifier = state.CodeVerifier; Console.WriteLine("Verifier: " + verifier); Console.WriteLine("-----------------------------------"); var state = GenState(); Console.WriteLine("state: " + state); //var loginURL = state.StartUrl; // Build URL var loginURL = Auth0URL; loginURL += $"authorize?response_type=code"; loginURL += $"&code_challenge={codeChallenge}"; loginURL += $"&code_challenge_method=S256"; loginURL += $"&client_id={Auth0ClientID_GH}"; loginURL += $"&scope=openid"; loginURL += $"&redirect_uri={redirectUri}"; loginURL += $"&state={state}"; Console.WriteLine($"Start login URL: {loginURL}"); var psi = new System.Diagnostics.ProcessStartInfo { FileName = loginURL, UseShellExecute = true }; System.Diagnostics.Process.Start(psi); // wait for the authorization response. var context = await listener.GetContextAsync(); var request = context.Request; var response = context.Response; Console.WriteLine("-----------------------------------"); Console.WriteLine($"AUTHORIZATION_CODE: "); var returnUrl = request.RawUrl.Contains("?code=") ? request.RawUrl : request.UrlReferrer.PathAndQuery; var AUTHORIZATION_CODE = returnUrl.Split('&').FirstOrDefault(_ => _.StartsWith("/?code=")).Split('=').Last().Trim(); //Console.WriteLine(AUTHORIZATION_CODE); Console.WriteLine($"State: "); var returnState = request.RawUrl.Split('&').FirstOrDefault(_ => _.StartsWith("state=")).Split('=').Last().Trim(); //Console.WriteLine(returnState); var IsAuthorized = returnState.Equals(state); IsAuthorized &= !string.IsNullOrEmpty(AUTHORIZATION_CODE); Console.WriteLine($"IsAuthorized: {IsAuthorized}"); Console.WriteLine("-----------------------------------"); var responseMessage = "This is not an authorized request!"; // Request Tokens if (IsAuthorized) { var restClient = new RestClient($"{Auth0URL}oauth/token"); var restRequest = new RestRequest(Method.POST); //restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded"); restRequest.AddParameter( "application/x-www-form-urlencoded", $"grant_type=authorization_code&client_id={Auth0ClientID_GH}&code_verifier={verifier}&code={AUTHORIZATION_CODE}&redirect_uri={redirectUri}", ParameterType.RequestBody ); var restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { var responseContent = restResponse.Content; var id_token = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(responseContent)["id_token"].ToString(); ID_TOKEN = id_token; Console.WriteLine("Successful login!"); //Console.WriteLine("id_token: " + id_token); Console.WriteLine("-----------------------------------"); responseMessage = "Signed in!. \n\nYou can close this window, and return to the Grasshopper."; } } //sends an HTTP response to the browser. string responseString = string.Format($"<html><head></head><body>{responseMessage}</body></html>"); var buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; await responseOutput.WriteAsync(buffer, 0, buffer.Length); responseOutput.Close(); listener.Stop(); return(ID_TOKEN); }
public async Task <HttpContext> GetContextAsync() { HttpListenerContext listenerContext = await _listener.GetContextAsync(); return(new HttpContext(listenerContext, _serializer)); }
private static async void DispatchHttpRequestsAsync(System.Net.HttpListener httpListener, CancellationToken cancellationToken) { // Create a request handler factory that uses basic authentication var requestHandlerFactory = new RequestHandlerFactory(); // Create WebDAV dispatcher var homeFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); var webDavDispatcher = new WebDavDispatcher(new DiskStore(homeFolder), requestHandlerFactory); // Determine the WebDAV username/password for authorization // (only when basic authentication is enabled) var webdavUsername = ConfigurationManager.AppSettings["webdav.username"] ?? "test"; var webdavPassword = ConfigurationManager.AppSettings["webdav.password"] ?? "test"; HttpListenerContext httpListenerContext; while (!cancellationToken.IsCancellationRequested && (httpListenerContext = await httpListener.GetContextAsync().ConfigureAwait(false)) != null) { // Determine the proper HTTP context IHttpContext httpContext; if (httpListenerContext.Request.IsAuthenticated) { httpContext = new HttpBasicContext(httpListenerContext, checkIdentity: i => i.Name == webdavUsername && i.Password == webdavPassword); } else { httpContext = new HttpContext(httpListenerContext); } // Dispatch the request await webDavDispatcher.DispatchRequestAsync(httpContext).ConfigureAwait(false); } }
public void Bind(string address) { _HttpListener.Prefixes.Add(address); _HttpListener.Start(); _ = _HttpListener.GetContextAsync().ContinueWith(_Listen, _CancelGetContext.Token); }
public void Bind(int port) { _HttpListener.Prefixes.Add($"http://127.0.0.1:{port}/"); _HttpListener.Start(); _ = _HttpListener.GetContextAsync().ContinueWith(_Listen, _CancelGetContext.Token); }
private async void ProcessRequestsAsync() { while (_listener.IsListening && CanAcceptMoreRequests) { Interlocked.Increment(ref _currentOutstandingAccepts); HttpListenerContext context; try { context = await _listener.GetContextAsync(); } catch (Exception ex) { // HttpListenerException happen if HttpListener has been disposed, or if the client disconnects mid request. // ObjectDisposedException happen if HttpListener has been disposed. // ApplicationException come from the thread pool if HttpListener tries to call BindHandle after the listener has been disposed. // Log it and try to keep going. Let IsListening break the loop. Interlocked.Decrement(ref _currentOutstandingAccepts); LogHelper.LogException(_logger, "Accept", ex); continue; } Interlocked.Decrement(ref _currentOutstandingAccepts); Interlocked.Increment(ref _currentOutstandingRequests); OffloadStartNextRequest(); // This needs to be separate from ProcessRequestsAsync so that async/await will clean up the execution context. // This prevents changes to Thread.CurrentPrincipal from leaking across requests. await ProcessRequestAsync(context); } }