public HttpWebServer(string[] prefixes, Func <HttpListenerRequest, string> method) { _listener = new HttpListener(); // URI prefixes are required, for example // "http://localhost:8080/index/". if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } // A responder method is required if (method == null) { throw new ArgumentException("method"); } foreach (var s in prefixes) { _listener.Prefixes.Add(s); } _responderMethod = method; _listener.Start(); }
public virtual async Task <bool> StartGetWebSocket(string uri) { if (!_isServerStarting) { _httpListener = new HttpListener(); _httpListener.Prefixes.Add("http://" + uri); _httpListener.Start(); while (true) { var httpListhenerContext = await _httpListener.GetContextAsync(); if (httpListhenerContext.Request.IsWebSocketRequest) { var context = await httpListhenerContext.AcceptWebSocketAsync(null); Debug.WriteLine("Client's server received a websocket handshake"); _webSocket = context.WebSocket; Debug.WriteLine($"Connected to {httpListhenerContext.Request.RemoteEndPoint.Address}"); _isServerStarting = true; return(true); } else { httpListhenerContext.Response.StatusCode = 400; httpListhenerContext.Response.Close(); Debug.WriteLine("Connection fail due to: It is not Websocket request"); } } } else { return(false); } }
private static HttpListener?MatchFromList(string path, List <ListenerPrefix>?list, out ListenerPrefix?prefix) { prefix = null; if (list == null) { return(null); } HttpListener?bestMatch = null; var bestLength = -1; foreach (var p in list) { if (p.Path.Length < bestLength || !path.StartsWith(p.Path, StringComparison.Ordinal)) { continue; } bestLength = p.Path.Length; bestMatch = p.Listener; prefix = p; } return(bestMatch); }
private void _Worker(RpcConfig rpcConfig) { if (!HttpListener.IsSupported) { throw new Exception("Your platform doesn't support [HttpListener]"); } _httpListener = new HttpListener(); foreach (var host in rpcConfig.Hosts ?? throw new InvalidOperationException()) { _httpListener.Prefixes.Add($"http://{host}:{rpcConfig.Port}/"); } _httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; _apiKey = rpcConfig.ApiKey ?? throw new InvalidOperationException(); _httpListener.Start(); while (_httpListener.IsListening) { try { _Handle(_httpListener.GetContext()); } catch (Exception e) { Console.Error.WriteLine(e); } } _httpListener.Stop(); }
private static HttpListener?MatchFromList(string?host, string path, List <ListenerPrefix>?list, out ListenerPrefix?prefix) { prefix = null; if (list == null) { return(null); } HttpListener?bestMatch = null; int bestLength = -1; foreach (ListenerPrefix p in list) { string ppath = p.Path !; if (ppath.Length < bestLength) { continue; } if (path.StartsWith(ppath, StringComparison.Ordinal)) { bestLength = ppath.Length; bestMatch = p._listener; prefix = p; } } return(bestMatch); }
public OAuthService(ILogger <SlackApp>?logger) { Logger = logger; CancellationSource = new CancellationTokenSource(); _httpListener = new HttpListener(); _httpListener.Prefixes.Clear(); }
public void Stop() { if (_listener != null) { _listener.Stop(); _listener.Close(); _listener = null; } }
public void Start(int port) { if (port > 0) { _listener = new HttpListener(); _port = port; Task.Factory.StartNew(StartListening); } }
public void GlobalSetup() { // Warm up Json engine internal type cache. JsonSerializer.Serialize(s_LargeInstance); _Server = new HttpListener(); _Server.Prefixes.Add("http://localhost:8018/benchmark/"); _Server.Start(); _Client = new HttpClient(); _ = Task.Run(ProcessRequests); }
public void Stop() { if (!_isStarted) { throw Error.InvalidOperation("Server not started"); } _httpListener?.Stop(); _listenerTask?.Wait(); _httpListener = null; _isStarted = false; }
public HttpResponseStream GetResponseStream() { if (_responseStream == null) { HttpListener?listener = _context._listener; if (listener == null) { return(new HttpResponseStream(_stream, _context.Response, true)); } _responseStream = new HttpResponseStream(_stream, _context.Response, listener.IgnoreWriteExceptions); } return(_responseStream); }
public bool BindContext(HttpListenerContext context) { HttpListenerRequest req = context.Request; ListenerPrefix? prefix; HttpListener? listener = SearchListener(req.Url, out prefix); if (listener == null) { return(false); } context._listener = listener; context.Connection.Prefix = prefix; return(true); }
public void Dispose() { if (_cts?.IsCancellationRequested == false) { _cts.Cancel(); Thread.Sleep(100); _cts.Dispose(); _cts = null; } if (_listener != null) { _listener.Stop(); _listener.Close(); _listener = null; } }
public static Task <string> Start(string[] args) { return(Task.Run <string>(() => { // Create a Http server and start listening for incoming connections listener = new HttpListener(); listener.Prefixes.Add(url); listener.Start(); Logger.Trace("Listening for connections on {0}", url); // Handle requests Task listenTask = HandleIncomingConnections(); listenTask.GetAwaiter().GetResult(); // Close the listener listener.Close(); return (accessToken == null ? "" : accessToken); })); }
public void Start(int port = 8125) { if (_disposed) { throw Error.Disposed(nameof(HttpServer)); } if (_isStarted) { throw Error.InvalidOperation("Server already started"); } _httpListener = new HttpListener(); _httpListener.Prefixes.Add($"http://*:{port}/"); _listenerTask = Task.Run(Listen); _isStarted = true; }
public HttpServer(string path, int port, ILog log, params IRequestHandler[] handlers) { _handlers = handlers; _cts = new CancellationTokenSource(); IndexFiles = new List <string> { "index.html", "index.htm", "default.html", "default.htm" }; _path = path; Port = port; _log = log; _handlerLock = new object(); _listener = new HttpListener(); _listener.Prefixes.Add($"http://localhost:{Port.ToString()}/"); Task.Run(() => Start(_cts.Token)); }
public void Start() { if (_pageData == null) { using var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("ChatCore.Resources.Web.index.html") !); _pageData = reader.ReadToEnd(); } if (_listener != null) { return; } _cancellationToken = new CancellationTokenSource(); _listener = new HttpListener { Prefixes = { $"http://localhost:{MainSettingsProvider.WEB_APP_PORT}/" } }; _listener.Start(); _logger.Log(LogLevel.Information, $"Listening on {string.Join(", ", _listener.Prefixes)}"); Task.Run(async() => { while (true) { try { _logger.LogInformation("Waiting for incoming request..."); var httpListenerContext = await _listener.GetContextAsync().ConfigureAwait(false); _logger.LogWarning("Request received"); await OnContext(httpListenerContext).ConfigureAwait(false); } catch (Exception e) { _logger.LogError(e, "WebLoginProvider errored."); } } // ReSharper disable once FunctionNeverReturns }).ConfigureAwait(false); }
public static void Start(string httpRoot) { s_httpRoot = httpRoot; if (s_serverRunning) { return; } s_serverRunning = true; s_listener = new HttpListener(); s_listener.Prefixes.Add(s_url); s_listener.Start(); Console.WriteLine("Started server at {0}.", s_url); Task requestHandler = HandleRequests(); requestHandler.GetAwaiter().GetResult(); s_listener.Close(); }
public void Start() { if (_pageData == null) { using var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("ChatCore.Resources.Web.index.html") !); _pageData = reader.ReadToEnd(); //_logger.LogInformation($"PageData: {pageData}"); } if (_listener != null) { return; } _cancellationToken = new CancellationTokenSource(); _listener = new HttpListener(); _listener.Prefixes.Add($"http://localhost:{_settings.WebAppPort}/"); Task.Run(() => { _listener.Start(); _listener.BeginGetContext(OnContext, null); }); }
private async Task OnReadInternal(int offset) { _timer.Change(Timeout.Infinite, Timeout.Infinite); // Continue reading until full header is received. // Especially important for multipart requests when the second part of the header arrives after a tiny delay // because the web browser has to measure the content length first. while (true) { try { await _ms.WriteAsync(_buffer, 0, offset).ConfigureAwait(false); if (_ms.Length > 32768) { Close(true); return; } } catch { CloseSocket(); Unbind(); return; } if (offset == 0) { CloseSocket(); Unbind(); return; } if (ProcessInput(_ms)) { if (!_context.HaveError) { _context.HttpListenerRequest.FinishInitialization(); } if (_context.HaveError || !_epl.BindContext(_context)) { Close(true); return; } var listener = _context.Listener; if (_lastListener != listener) { RemoveConnection(); listener.AddConnection(this); _lastListener = listener; } _contextBound = true; listener.RegisterContext(_context); return; } offset = await Stream.ReadAsync(_buffer, 0, BufferSize).ConfigureAwait(false); } }
public HttpConnection(HttpListener?listener) { this.listener = listener; HttpRequests = GetHttpRequests(); }
public void Dispose() { _listener?.Close(); _listener = null; }
private void OnReadInternal(IAsyncResult ares) { _timer.Change(Timeout.Infinite, Timeout.Infinite); int nread; try { nread = _stream.EndRead(ares); _memoryStream !.Write(_buffer !, 0, nread); if (_memoryStream.Length > 32768) { SendError(HttpStatusDescription.Get(400), 400); Close(true); return; } } catch { if (_memoryStream != null && _memoryStream.Length > 0) { SendError(); } if (_socket != null) { CloseSocket(); Unbind(); } return; } if (nread == 0) { CloseSocket(); Unbind(); return; } if (ProcessInput(_memoryStream)) { if (!_context.HaveError) { _context.Request.FinishInitialization(); } if (_context.HaveError) { SendError(); Close(true); return; } if (!_epl.BindContext(_context)) { const int NotFoundErrorCode = 404; SendError(HttpStatusDescription.Get(NotFoundErrorCode), NotFoundErrorCode); Close(true); return; } HttpListener listener = _context._listener !; if (_lastListener != listener) { RemoveConnection(); listener.AddConnection(this); _lastListener = listener; } _contextBound = true; listener.RegisterContext(_context); return; } _stream.BeginRead(_buffer !, 0, BufferSize, s_onreadCallback, this); }
private HttpListener?SearchListener(Uri?uri, out ListenerPrefix?prefix) { prefix = null; if (uri == null) { return(null); } string host = uri.Host; int port = uri.Port; string path = WebUtility.UrlDecode(uri.AbsolutePath); string pathSlash = path.EndsWith('/') ? path : path + "/"; HttpListener?bestMatch = null; int bestLength = -1; if (host != null && host != "") { Dictionary <ListenerPrefix, HttpListener> localPrefixes = _prefixes; foreach (ListenerPrefix p in localPrefixes.Keys) { string ppath = p.Path !; if (ppath.Length < bestLength) { continue; } if (p.Host != host || p.Port != port) { continue; } if (path.StartsWith(ppath, StringComparison.Ordinal) || pathSlash.StartsWith(ppath, StringComparison.Ordinal)) { bestLength = ppath.Length; bestMatch = localPrefixes[p]; prefix = p; } } if (bestLength != -1) { return(bestMatch); } } List <ListenerPrefix>?list = _unhandledPrefixes; bestMatch = MatchFromList(host, path, list, out prefix); if (path != pathSlash && bestMatch == null) { bestMatch = MatchFromList(host, pathSlash, list, out prefix); } if (bestMatch != null) { return(bestMatch); } list = _allPrefixes; bestMatch = MatchFromList(host, path, list, out prefix); if (path != pathSlash && bestMatch == null) { bestMatch = MatchFromList(host, pathSlash, list, out prefix); } if (bestMatch != null) { return(bestMatch); } return(null); }
private HttpListener?SearchListener(Uri uri, out ListenerPrefix?prefix) { prefix = null; if (uri == null) { return(null); } var host = uri.Host; var port = uri.Port; var path = WebUtility.UrlDecode(uri.AbsolutePath); var pathSlash = path[path.Length - 1] == '/' ? path : path + "/"; HttpListener?bestMatch = null; var bestLength = -1; if (!string.IsNullOrEmpty(host)) { var result = _prefixes; foreach (var p in result.Keys) { if (p.Path.Length < bestLength) { continue; } if (p.Host != host || p.Port != port) { continue; } if (!path.StartsWith(p.Path, StringComparison.Ordinal) && !pathSlash.StartsWith(p.Path, StringComparison.Ordinal)) { continue; } bestLength = p.Path.Length; bestMatch = result[p]; prefix = p; } if (bestLength != -1) { return(bestMatch); } } var list = _unhandled; bestMatch = MatchFromList(path, list, out prefix); if (path != pathSlash && bestMatch == null) { bestMatch = MatchFromList(pathSlash, list, out prefix); } if (bestMatch != null) { return(bestMatch); } list = _all; bestMatch = MatchFromList(path, list, out prefix); if (path != pathSlash && bestMatch == null) { bestMatch = MatchFromList(pathSlash, list, out prefix); } return(bestMatch); }
public void Dispose() { _httpListener = null; CancellationSource.Dispose(); }