static void Main() { Console.Title = "Samples.CustomChecks.3rdPartySystem"; Console.WriteLine("Press enter key to toggle the server to return a error or success"); Console.WriteLine("Press any key to exit"); using (listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:57789/"); listener.Start(); listener.BeginGetContext(ListenerCallback, listener); while (true) { ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); if (key.Key != ConsoleKey.Enter) { return; } listener.Close(); if (isReturningOk) { Console.WriteLine("\r\nCurrently returning success"); } else { Console.WriteLine("\r\nCurrently returning error"); } isReturningOk = !isReturningOk; } } }
void OnDestroy() { if (listener != null) { listener.Close(); listener = null; } }
public static void AddPrefix(ILogger logger, string prefix, HttpListener listener) { lock (ip_to_endpoints) { AddPrefixInternal(logger, prefix, listener); } }
static void StartListener() { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:57789/"); listener.Start(); listener.BeginGetContext(ListenerCallback, listener); }
public static void AddListener(HttpListener listener) { ArrayList added = new ArrayList(); try { lock (ip_to_endpoints) { foreach (string prefix in listener.Prefixes) { AddPrefixInternal(prefix, listener); added.Add(prefix); } } } catch { foreach (string prefix in added) { RemovePrefix(prefix, listener); } throw; } }
private ArrayList _unhandled; // List<ListenerPrefix> unhandled; host = '*' #endregion Fields #region Constructors public EndPointListener(HttpListener listener, IPAddress addr, int port, bool secure) { Listener = listener; if (secure) { #if SSL this.secure = secure; cert = listener.LoadCertificateAndKey (addr, port); #else throw new Exception("SSL is not supported"); #endif } _endpoint = new IPEndPoint(addr, port); _sock = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _sock.Bind(_endpoint); _sock.Listen(500); var args = new SocketAsyncEventArgs {UserToken = this}; args.Completed += OnAccept; Socket dummy = null; Accept(_sock, args, ref dummy); _prefixes = new Hashtable(); _unregistered = new Dictionary<HttpConnection, HttpConnection>(); }
void Awake() { listener = new HttpListener(); listener.Prefixes.Add("http://*:7663/"); listener.Start(); listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); }
public static void AddPrefix(string prefix, HttpListener listener) { lock (_ipToEndpoints) { AddPrefixInternal(prefix, listener); } }
private static EndPointListener getEndPointListener ( IPAddress address, int port, HttpListener httpListener, bool secure) { Dictionary<int, EndPointListener> endpoints = null; if (_ipToEndpoints.ContainsKey (address)) { endpoints = _ipToEndpoints [address]; } else { endpoints = new Dictionary<int, EndPointListener> (); _ipToEndpoints [address] = endpoints; } EndPointListener epListener = null; if (endpoints.ContainsKey (port)) { epListener = endpoints [port]; } else { epListener = new EndPointListener ( address, port, secure, httpListener.CertificateFolderPath, httpListener.DefaultCertificate); endpoints [port] = epListener; } return epListener; }
private void ListenThread() { try { listener = new HttpListener(); foreach (string prefix in prefixes) { listener.Prefixes.Add(prefix); } listener.Start(); while (true) { HttpListenerContext context = listener.GetContext(); Debug.LogFormat("Recieved request from {0}.", context.Request.RemoteEndPoint.ToString()); context.Response.StatusCode = 200; lock (waitingContexts) { waitingContexts.AddLast(context); } } } catch(Exception e) { Debug.LogErrorFormat("Web server error at {0}.", e.Source); Debug.LogError(e.Message, this); } }
public void FixtureSetup() { _listener = new HttpListener(_uri.OriginalString); _listener.Start(); _server = new Tracker(); _server.RegisterListener(_listener); _listener.Start(); }
public Server() { this.httpListener = new HttpListener(); this.httpListener.Prefixes.Add("http://localhost:8080/"); this.httpListener.Prefixes.Add("http://127.0.0.1:8080/"); this.httpListener.Prefixes.Add("http://test.localhost:8080/"); }
public Listener () { EndPoints = new List<IPEndPoint> (); listener = new HttpListener (); listener.Prefixes.Add (KeepAliveTest.URL); listener.Start (); listener.BeginGetContext (Handle, null); }
public void Configure(string[] prefixes, string vdir, string pdir) { _virtualDir = vdir; _physicalDir = pdir; _listener = new HttpListener(); foreach (string prefix in prefixes) _listener.Prefixes.Add(prefix); }
public HttpListener CreateListener(List<string> addresses) { var listener = new HttpListener(); addresses.ForEach(a => listener.Prefixes.Add(a)); listener.Start(); return listener; }
public Server(string prefix) { if (!HttpListener.IsSupported) { Console.WriteLine("server is not supported"); } listener = new HttpListener(); listener.Prefixes.Add(prefix); resourceLocator = new HttpResourceLocator(); }
/// <summary> /// Create an instance of <see cref="WebAppServer"/>. /// </summary> /// <param name="urlReservation"> /// The URL reservation to listen on. This string is similar to a URL, but the /// hostname may be a strong wildcard ('+') or a weak wildcard ('*'). E.g. "http://+:8080/". /// </param> public WebAppServer(string urlReservation) { _urlRegex = new Regex("^" + urlReservation.Replace("*", ".*?").Replace("+", ".*?"), RegexOptions.IgnoreCase); _listener = new HttpListener(); _listener.Prefixes.Add(urlReservation); _disconnectHandler = new DisconnectHandler(_listener); var uri = new Uri(urlReservation.Replace("*", "localhost").Replace("+", "localhost")); _webAppConfiguration = new WebAppConfiguration(uri); StaticFiles = new StaticFileSpecCollection(); }
public static void RemoveListener(ILogger logger, HttpListener listener) { lock (ip_to_endpoints) { foreach (string prefix in listener.Prefixes) { RemovePrefixInternal(logger, prefix, listener); } } }
public NetEventHandler() { BaseUrl = Net.GetUrl(Net.GetIp(IPType.All), Net.FindPort(), "").ToString(); ServicePointManager.DefaultConnectionLimit = 100; _httpListener = new HttpListener(); _httpListener.Prefixes.Add(BaseUrl); _httpListener.Start(); ThreadPool.QueueUserWorkItem(Listen); }
public ListenerScope (Action<HttpListenerContext> processor) { this.processor = processor; this.listener = new HttpListener (); this.listener.Prefixes.Add ("http://*:8001/"); this.listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; this.listener.Start (); this.listener.BeginGetContext (this.RequestHandler, null); }
public void StartListener (Object args) { HttpListener listener = new HttpListener (); string prefix = string.Format ("http://*:8880/{0}/", args); listener.Prefixes.Add (prefix); listener.Start (); for (; ; ) { HttpListenerContext ctx = listener.GetContext (); new Thread (new Worker (ctx).ProcessRequest).Start (); } }
public void Start() { Debug.Log("Start HttpServer"); if (listener == null) { listener = new HttpListener(); listener.Prefixes.Add(string.Format("http://{0}:{1}/", "localhost", 8080)); } listener.Start(); listener.BeginGetContext(OnGetContext, listener); }
static void AddPrefixInternal (string p, HttpListener listener) { ListenerPrefix lp = new ListenerPrefix (p); if (lp.Path.IndexOf ('%') != -1) throw new HttpListenerException (400, "Invalid path."); if (lp.Path.IndexOf ("//", StringComparison.Ordinal) != -1) // TODO: Code? throw new HttpListenerException (400, "Invalid path."); // Always listens on all the interfaces, no matter the host name/ip used. EndPointListener epl = GetEPListener (IPAddress.Any, lp.Port, listener, lp.Secure); epl.AddPrefix (lp, listener); }
private static void addPrefix (string uriPrefix, HttpListener httpListener) { var pref = new HttpListenerPrefix (uriPrefix); if (pref.Path.IndexOf ('%') != -1) throw new HttpListenerException (400, "Invalid path."); // TODO: Code? if (pref.Path.IndexOf ("//", StringComparison.Ordinal) != -1) throw new HttpListenerException (400, "Invalid path."); // TODO: Code? // Always listens on all the interfaces, no matter the host name/ip used. var epl = getEndPointListener (IPAddress.Any, pref.Port, pref.IsSecure, httpListener); epl.AddPrefix (pref, httpListener); }
static void AddPrefixInternal (string p, HttpListener listener) { ListenerPrefix lp = new ListenerPrefix (p); if (lp.Path.IndexOf ('%') != -1) throw new HttpListenerException (400, "Invalid path."); if (lp.Path.IndexOf ("//", StringComparison.Ordinal) != -1) // TODO: Code? throw new HttpListenerException (400, "Invalid path."); // listens on all the interfaces if host name cannot be parsed by IPAddress. EndPointListener epl = GetEPListener (lp.Host, lp.Port, listener, lp.Secure); epl.AddPrefix (lp, listener); }
private static void addPrefix (string uriPrefix, HttpListener listener) { var pref = new HttpListenerPrefix (uriPrefix); if (pref.Path.IndexOf ('%') != -1) throw new HttpListenerException (400, "Invalid path."); // TODO: Code? if (pref.Path.IndexOf ("//", StringComparison.Ordinal) != -1) throw new HttpListenerException (400, "Invalid path."); // TODO: Code? // Listens on all the interfaces if host name cannot be parsed by IPAddress. var lsnr = getEndPointListener (pref.Host, pref.Port, listener, pref.IsSecure); lsnr.AddPrefix (pref, listener); }
public HttpServer(string prefix) { if (!HttpListener.IsSupported) { // Requires at least a Windows XP with Service Pack 2 throw new NotSupportedException("The Http Server cannot run on this operating system."); } _httpListener = new HttpListener(); // Add the prefixes to listen to _httpListener.Prefixes.Add(prefix); _resourceLocator = new HttpResourceLocator(); }
private static void addPrefix (string uriPrefix, HttpListener listener) { var pref = new HttpListenerPrefix (uriPrefix); var path = pref.Path; if (path.IndexOf ('%') != -1) throw new HttpListenerException (87, "Includes an invalid path."); if (path.IndexOf ("//", StringComparison.Ordinal) != -1) throw new HttpListenerException (87, "Includes an invalid path."); // Listens on all the interfaces if host name cannot be parsed by IPAddress. getEndPointListener (pref, listener).AddPrefix (pref, listener); }
static void Main () { HttpListener listener = new HttpListener (); listener.IgnoreWriteExceptions = true; listener.Prefixes.Add ("http://*:8081/"); listener.Start (); listener.BeginGetContext (RequestHandler, listener); while (true) { Thread.Sleep (250); if (File.Exists ("stop-server.tmp")) break; } listener.Close (); File.Create ("finish-server.tmp").Close (); }
public HttpBackend(App app, IPAddress ip, int port = 80) : base(app) { Server = new HttpListener(); Server.Prefixes.Add($"http://{ ip.ToString() }:{ port }/"); }
public Server(int port) { portN = port; http_listener = new HttpListener(); }
public WebSocketListener(HttpListener http) { this.http = http; }
public async Task <TokenResponse> Authenticate() { // Generates state and PKCE values. var state = CryptoRandom.CreateUniqueId(); // Creates a redirect URI using an available port on the loopback address. var redirectUri = $"http://{IPAddress.Loopback}:{GetRandomUnusedPort()}/"; Console.WriteLine("redirect URI: " + redirectUri); var request = new AuthorizeRequest(_discoResponse.AuthorizeEndpoint); var url = request.CreateAuthorizeUrl( clientId: OpenIdConstants.ClientId, responseType: OidcConstants.ResponseTypes.Code, responseMode: OidcConstants.ResponseModes.Query, redirectUri: redirectUri, state: state, nonce: Guid.NewGuid().ToString(), scope: "openid profile offline_access" ); // Creates an HttpListener to listen for requests on that redirect URI. var http = new HttpListener(); http.Prefixes.Add(redirectUri); Console.WriteLine("Listening.."); http.Start(); // Opens request in the browser. System.Diagnostics.Process.Start(url); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); // Sends an HTTP response to the browser. var response = context.Response; var responseString = "<html><head><meta http-equiv=\'refresh\' content=\'10;url=https://google.com\'></head><body>Please return to the app.</body></html>"; var buffer = 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(); Console.WriteLine("HTTP server stopped."); }); var authorizeResponse = new AuthorizeResponse(context.Request.RawUrl); // Checks for errors. if (authorizeResponse.Error != null) { var message = $"OAuth authorization error: {authorizeResponse.Error}."; throw new Exception(message); } // extracts the code var code = authorizeResponse.Code; if (code == null || authorizeResponse.State == null) { var message = "Malformed authorization response. Missing code or incoming state"; throw new Exception(message); } // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (authorizeResponse.State != state) { var message = $"Received request with invalid state ({authorizeResponse.State})"; throw new Exception(message); } Console.WriteLine("Authorization code: " + code); var tokenEndpointClient = new TokenClient(_discoResponse.TokenEndpoint, OpenIdConstants.ClientId, OpenIdConstants.ClientSecret, AuthenticationStyle.PostValues); var tokenResponse = await tokenEndpointClient.RequestAuthorizationCodeAsync(code, redirectUri); var userInfoEndpointClient = new UserInfoClient(_discoResponse.UserInfoEndpoint); var userInfoResponse = await userInfoEndpointClient.GetAsync(tokenResponse.AccessToken); Console.WriteLine("AccessToken = {0}", tokenResponse.AccessToken); Console.WriteLine("IdentityToken = {0}", tokenResponse.IdentityToken); Console.WriteLine("RefreshToken = {0}", tokenResponse.RefreshToken); Console.WriteLine("TokenType = {0}", tokenResponse.TokenType); Console.WriteLine("UserClaims.Count = {0}", userInfoResponse.Claims.Count()); return(tokenResponse); }
public HttpBackend(App app) : base(app) { Server = new HttpListener(); Server.Prefixes.Add("http://localhost:8080/"); // safe }
public HttpResponseStreamTests() { _factory = new HttpListenerFactory(); _listener = _factory.GetListener(); _helper = new GetContextHelper(_listener, _factory.ListeningUrl); }
public HttpFileServer(string rootPath, int port, string[] PrefixIPs, bool ElfLoader) { Console.WriteLine("rootPath: " + rootPath); this.RootPath = rootPath; http = new HttpListener(); if (!ElfLoader) { string PrefixString = "http://localhost:" + port + "/"; MainWindow.AddToLogWeb("start serving as: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } if (!ElfLoader) { string PrefixString = "http://127.0.0.1:" + port + "/"; MainWindow.AddToLogWeb("start serving as: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } if (MainWindow.Instance.AppSettings.UseLocalIP && !String.IsNullOrEmpty(MainWindow.Instance.AppSettings.LocalIP)) { string PrefixString = "http://" + MainWindow.Instance.AppSettings.LocalIP + ":" + port + "/"; MainWindow.AddToLogWeb("start serving as configured: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } if (PrefixIPs != null && PrefixIPs.Length > 0) { foreach (string ip in PrefixIPs) { string PrefixString = "http://" + ip + ":" + port + "/"; Console.WriteLine("Prefix-IP: " + ip); MainWindow.AddToLogWeb("start serving as: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } } try { http.Start(); if (ElfLoader) { http.BeginGetContext(requestWaitELFloader, null); } else { http.BeginGetContext(requestWait, null); } } catch (System.Net.HttpListenerException he) { string error = MainWindow.ErrorTag + " There was a problem while starting the webserver, maybe a wrong IP was given, will try to get working IPs from the system instead: " + he.ToString(); Console.WriteLine(error); MainWindow.AddToLogWeb(error); http = new HttpListener(); string[] PrefixIPsNew = network.GetAllLocalIPv4(); if (!ElfLoader) { string PrefixString = "http://localhost:" + port + "/"; MainWindow.AddToLogWeb("start serving as: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } if (!ElfLoader) { string PrefixString = "http://127.0.0.1:" + port + "/"; MainWindow.AddToLogWeb("start serving as: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } if (PrefixIPsNew != null && PrefixIPsNew.Length > 0) { foreach (string ip in PrefixIPsNew) { string PrefixString = "http://" + ip + ":" + port + "/"; Console.WriteLine("Prefix-IP: " + ip); MainWindow.AddToLogWeb("start serving as: " + PrefixString); if (!http.Prefixes.Contains(PrefixString)) { http.Prefixes.Add(PrefixString); } } } try { http.Start(); if (ElfLoader) { http.BeginGetContext(requestWaitELFloader, null); } else { http.BeginGetContext(requestWait, null); } } catch (Exception ex) { error = MainWindow.ErrorTag + " There was a problem while starting the webserver: " + ex.ToString(); Console.WriteLine(error); MainWindow.AddToLogWeb(error); } } catch (Exception ex) { string error = MainWindow.ErrorTag + " There was a problem while starting the webserver: " + ex.ToString(); Console.WriteLine(error); MainWindow.AddToLogWeb(error); } }
public void Dispose() { _listener.Close(); _listener = null; }
/// <summary> /// Start http challenge server. /// </summary> /// <param name="port"> Port to listen on, default 80 </param> /// <param name="controlKey"> Control key to command process to quit </param> /// <param name="checkKey"> Check key to test server response </param> /// <returns> </returns> public bool Start(ServiceConfig serverConfig, string controlKey = null, string checkKey = null) { #if DEBUG _debugMode = true; #endif _lastRequestTime = DateTime.Now; try { if (controlKey != null) { _controlKey = controlKey; } if (checkKey != null) { _checkKey = checkKey; } _httpListener = new HttpListener(); _baseUri = $"http://{serverConfig.Host}:{serverConfig.Port}/api/"; _apiClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }); _apiClient.DefaultRequestHeaders.Add("User-Agent", "Certify/HttpChallengeServer"); _apiClient.Timeout = new TimeSpan(0, 0, 20); var uriPrefix = $"http://+:{serverConfig.HttpChallengeServerPort}{_challengePrefix}"; _httpListener.Prefixes.Add(uriPrefix); _challengeResponses = new Dictionary <string, string>(); _httpListener.Start(); Log($"Http Challenge Server Started: {uriPrefix}", true); Log($"Control Key: {_controlKey}: Check Key: {_checkKey}"); _serverTask = Task.Run(ServerTask); var stateTimer = new Timer((object stateInfo) => { Log("Checking for auto close."); var time = _lastRequestTime - DateTime.Now; if (Math.Abs(time.TotalSeconds) > 60) { Log("No requests recently, stopping server."); Stop(); } }, null, 1000 * 10, 1000 * 10); return(true); } catch (Exception exp) { //could not start listener, port may be in use System.Diagnostics.Debug.WriteLine($"Http Challenge server error: {exp}"); try { // try to stop the listener, if a collision on port etc then listener will already be disposed _httpListener.Stop(); } catch { } _httpListener.Close(); _httpListener = null; _apiClient.Dispose(); _apiClient = null; Log("Failed to Start Http Challenge Server"); } return(false); }
private static void DoLogIn() { if (ClientID == null) { RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Clussman Productions\MesaSuite"); string clientIDString = key.GetValue("ClientID") as string; if (!Guid.TryParse(clientIDString, out Guid clientID)) { ClientID = Guid.NewGuid(); key.SetValue("ClientID", ClientID.ToString()); frmRegister register = new frmRegister(); register.ClientID = ClientID.Value; register.ShowDialog(); } else { ClientID = clientID; } } int openPort = -1; IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] connections = properties.GetActiveTcpConnections(); IPEndPoint[] listeners = properties.GetActiveTcpListeners(); foreach (int port in PORTS) { if (connections.Any(connection => connection.LocalEndPoint.Port == port) || listeners.Any(ipListener => ipListener.Port == port)) { continue; } openPort = port; break; } if (openPort == -1) { throw new Exception("Could not open a port for authentication"); } Guid state = Guid.NewGuid(); frmLogin login = new frmLogin(); login.Port = openPort; login.ClientID = ClientID.Value; login.State = state; login.DialogResult = DialogResult.Cancel; HttpListener listener = null; try { listener = new HttpListener(); ListenForResponse(listener, login, openPort, state); DialogResult result = login.ShowDialog(); if (result == DialogResult.Cancel) { return; } } finally { listener.Close(); } if (!string.IsNullOrEmpty(AuthToken)) { AuthenticationStatus = AuthenticationStatuses.LoggedIn; } }
static int Main(string[] args) { var domain = AppDomain.CurrentDomain; if (domain.IsDefaultAppDomain()) { Console.WriteLine("Switching to secondary AppDomain..."); return(SwitchDomain(domain)); } Console.WriteLine("Now running in secondary AppDomain.\n"); var addresses = new List <IPAddress>(); addresses.Add(IPAddress.Loopback); addresses.AddRange(Dns.GetHostAddresses("").Where(x => x.AddressFamily == AddressFamily.InterNetwork)); using (var listener = new HttpListener()) { foreach (var address in addresses) { var url = String.Format("http://{0}:12345/", address); listener.Prefixes.Add(url); Console.WriteLine("{0}", url); } listener.Start(); Console.WriteLine(); while (true) { var context = listener.GetContext(); using (var response = context.Response) { var request = context.Request; Console.WriteLine("{0}", request.RawUrl); if (request.RawUrl == "/") { response.ContentEncoding = Encoding.UTF8; response.ContentType = "text/html"; using (var reader = new StreamReader(File.OpenRead("index.cshtml"))) { using (var writer = new StreamWriter(response.OutputStream, response.ContentEncoding)) { writer.Write( RazorEngine.Engine.Razor.RunCompile( reader.ReadToEnd(), "templateKey", null, new { Title = "HttpListener1" } ) ); } } } else if (request.RawUrl == "/sse") { response.ContentEncoding = Encoding.UTF8; response.ContentType = "text/event-stream"; var writer = new StreamWriter(response.OutputStream, response.ContentEncoding); writer.Write("data: Testing!\n\n"); writer.Flush(); } else { response.ContentEncoding = Encoding.UTF8; response.ContentType = "text/html"; response.StatusCode = 404; using (var writer = new StreamWriter(response.OutputStream, response.ContentEncoding)) writer.Write("404 Not Found"); } } } } return(0); }
public SpanCollector(HttpListener listener) { _task = new Task(() => Handle(listener)); _task.Start(); }
// https://github.com/googlesamples/oauth-apps-for-windows/blob/master/OAuthDesktopApp/OAuthDesktopApp/MainWindow.xaml.cs public static async UniTask <Code> Authorize(string scope, string clientId, string message) { var codeVerifier = RandomDataBase64url(32); var state = RandomDataBase64url(32); var codeChallenge = Base64urlencodeNoPadding(Sha256(codeVerifier)); const string codeChallengeMethod = "S256"; var redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, GetRandomUnusedPort()); // Creates an HttpListener to listen for requests on that redirect URI. var http = new HttpListener(); http.Prefixes.Add(redirectURI); http.Start(); // Creates the OAuth 2.0 authorization request. var authorizationRequest = "https://accounts.google.com/o/oauth2/v2/auth" + "?scope=" + scope + "&redirect_uri=" + System.Uri.EscapeDataString(redirectURI) + "&response_type=code" + "&state=" + state + "&client_id=" + clientId + "&code_challenge=" + codeChallenge + "&code_challenge_method=" + codeChallengeMethod; Application.OpenURL(authorizationRequest); var context = await http.GetContextAsync(); // Sends an HTTP response to the browser. var response = context.Response; var responseString = $"<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>{message}</body></html>"; var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; var responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); }); if (context.Request.QueryString.Get("error") != null) { Debug.Log(string.Format("OAuth authorization error: {0}.", context.Request.QueryString.Get("error"))); return(null); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { Debug.Log("Malformed authorization response. " + context.Request.QueryString); return(null); } // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. var incoming_state = context.Request.QueryString.Get("state"); if (incoming_state != state) { Debug.Log(string.Format("Received request with invalid state ({0})", incoming_state)); return(null); } var code = context.Request.QueryString.Get("code"); return(new Code() { code = code, codeVerifier = codeVerifier, redirectUri = redirectURI }); }
public void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); listener.BeginGetContext(ListenerCallback, listener); var ssid = Guid.NewGuid(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; string data = ""; if (Environment.OSVersion.Platform == PlatformID.Unix) { if (string.Compare(request.HttpMethod, "get", true) == 0) { data = request.RawUrl.Substring(8); data = HttpUtility.UrlDecode(data); } } else { data = request.QueryString["d"]; } if (string.IsNullOrEmpty(data)) { using (var reader = new StreamReader(request.InputStream, request.ContentEncoding)) { data = reader.ReadToEnd(); data = HttpUtility.ParseQueryString(data)["d"]; } } int gameId, serverId, statuscode; var requestParam = RequestParse.Parse(request.RemoteEndPoint.Address.ToString(), request.RawUrl, data, out gameId, out serverId, out statuscode); if (statuscode != (int)HttpStatusCode.OK) { response.StatusCode = statuscode; response.Close(); return; } requestParam["UserHostAddress"] = request.RemoteEndPoint.Address.ToString(); requestParam["ssid"] = ssid.ToString("N"); requestParam["http"] = "1"; var clientConnection = new HttpClientConnection { Context = context, SSID = ssid, Param = requestParam }; clientConnection.TimeoutTimer = new Timer(TimeoutSendback, clientConnection, httpProxyTimeout, Timeout.Infinite); byte[] paramData = Encoding.ASCII.GetBytes(RequestParse.ToQueryString(requestParam)); pool[ssid] = clientConnection; try { gsConnectionManager.Send(gameId, serverId, paramData); } catch (Exception ex) { TraceLog.WriteError("无法连接游服error:{0}", ex); var responseData = RequestParse.CtorErrMsg(errmsg, requestParam); SendDataBack(ssid, responseData, 0, responseData.Length); } }
public FakeHttpServer(int port, ICollection <FakeHttpServerResponse> responseList) { Listener = new HttpListener(); Listener.Prefixes.Add("http://localhost:" + port + "/"); _responseList = responseList; }
public HttpListenerObservable(string url) { this.listener = new HttpListener(); this.listener.Prefixes.Add(url); }
private static void RemoteCompileService() { var udpClient = new UdpClient(4321); var thread = new Thread(() => { while (true) { try { IPEndPoint endpoint = null; var bytes = udpClient.Receive(ref endpoint); var message = Encoding.ASCII.GetString(bytes); if (message == "request compiler") { var result = Encoding.ASCII.GetBytes("provide compiler"); udpClient.Send(result, result.Length, new IPEndPoint(endpoint.Address, 4321)); Console.WriteLine("Providing compiler services for " + endpoint.Address); } } catch (Exception e) { Console.WriteLine(e); } } }); thread.IsBackground = true; thread.Start(); var server = new HttpListener(); server.Prefixes.Add("http://+:8080/"); try { server.Start(); } catch (HttpListenerException ex) { var args = "http add urlacl http://+:8080/ user=Everyone listen=yes"; var psi = new ProcessStartInfo("netsh", args); psi.Verb = "runas"; psi.CreateNoWindow = true; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = true; Process.Start(psi).WaitForExit(); args = "advfirewall firewall add rule name=\"Port 8080 for Protogame Remote Compiler\" dir=in action=allow protocol=TCP localport=8080"; psi = new ProcessStartInfo("netsh", args); psi.Verb = "runas"; psi.CreateNoWindow = true; psi.WindowStyle = ProcessWindowStyle.Hidden; psi.UseShellExecute = true; Process.Start(psi).WaitForExit(); server = new HttpListener(); server.Prefixes.Add("http://+:8080/"); server.Start(); } Console.WriteLine("Remote compiler for Protogame started on port 4321 (UDP) and port 8080 (TCP)"); while (true) { var context = server.GetContext(); var request = context.Request; var response = context.Response; Console.WriteLine("Request: " + request.RawUrl); string input = null; using (var reader = new StreamReader(request.InputStream)) { input = reader.ReadToEnd(); } switch (request.Url.AbsolutePath) { case "/compileeffect": { var platform = (TargetPlatform)Convert.ToInt32(request.QueryString["platform"]); var effect = new EffectAsset( null, "effect", input, null, true); var compiler = new EffectAssetCompiler(); try { compiler.Compile(effect, platform); } catch (Exception ex) { response.StatusCode = 500; var result = Encoding.ASCII.GetBytes(ex.Message); response.ContentLength64 = result.Length; response.OutputStream.Write(result, 0, result.Length); response.Close(); break; } try { response.ContentLength64 = effect.PlatformData.Data.Length; response.OutputStream.Write(effect.PlatformData.Data, 0, effect.PlatformData.Data.Length); response.Close(); } catch (HttpListenerException) { } break; } case "/compilefont": { var platform = (TargetPlatform)Convert.ToInt32(request.QueryString["platform"]); var content = input.Split('\0'); var fontName = content[0]; var fontSize = int.Parse(content[1]); var spacing = int.Parse(content[2]); var useKerning = bool.Parse(content[3]); var font = new FontAsset( null, "font", fontName, fontSize, useKerning, spacing, null); var compiler = new FontAssetCompiler(); try { compiler.Compile(font, platform); } catch (Exception ex) { response.StatusCode = 500; var result = Encoding.ASCII.GetBytes(ex.Message); response.ContentLength64 = result.Length; response.OutputStream.Write(result, 0, result.Length); response.Close(); break; } try { response.ContentLength64 = font.PlatformData.Data.Length; response.OutputStream.Write(font.PlatformData.Data, 0, font.PlatformData.Data.Length); response.Close(); } catch (HttpListenerException) { } break; } default: { response.StatusCode = 404; var result = Encoding.ASCII.GetBytes("not found"); response.ContentLength64 = result.Length; response.OutputStream.Write(result, 0, result.Length); response.Close(); break; } } } }
static void Main(string[] args) { ServiceManager manager = new ServiceManager(); manager.ReadSetting("serviceSetting.xml"); //manager.SaveSetting("serviceSetting.xml"); //AddAddress("https://*:8082/", System.Environment.MachineName, System.Environment.UserName); using (HttpListener server = new HttpListener()) { server.IgnoreWriteExceptions = true; server.Prefixes.Add(@"http://*:8081/"); try { server.Start(); } catch (Exception e) { //这里一般产生的是这个端口已经被占用,之类的错误 //可以用这里的异常来检测多实例,防止可能的数据库被损坏 Console.WriteLine(e); return; } //服务的启动放在后面,防止多个实例碰撞 foreach (var srv in manager.ActiveServices) { srv.Start(); } for (;;) { var result = server.GetContext(); bool isHandled = false; //Console.WriteLine(result); foreach (var srv in manager.ActiveServices) { if (srv is IDomainProxy) { var proxy = srv as IDomainProxy; if (proxy.OnHttpRequest(result)) { isHandled = true; break; } } } if (!isHandled && result.Request.RawUrl.Equals("/quit")) { using (StreamWriter writer = new StreamWriter(result.Response.OutputStream)) { writer.Write("Service Terminated."); writer.Close(); result.Response.Close(); } break; } if (!isHandled) { result.Response.StatusCode = 404; using (StreamWriter writer = new StreamWriter(result.Response.OutputStream)) { writer.Write("404."); writer.Close(); result.Response.Close(); } continue; } } foreach (var srv in manager.ActiveServices) { Console.WriteLine($"Waiting For {srv.Alias}..."); srv.Stop(); } manager.ActiveServices.Clear(); GC.Collect(); server.Stop(); Console.WriteLine("StalkerProject Terminated.\n\n\n\n\n\n\n"); } }
void DoWork() { try { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:" + port + "/"); listener.Start(); } catch (System.Exception) { PluginLoader.Log("An error has ocurrend when initializing the HTTPListener!"); return; } BLStudio.Instance.onRemovePrimitivie += primitiveRemoved; BLStudio.Instance.onModifiedPart += PartModified; while (true) { try { HttpListenerContext ctx = listener.GetContext(); HttpListenerRequest req = ctx.Request; HttpListenerResponse resp = ctx.Response; using (StreamWriter writer = new StreamWriter(resp.OutputStream)) { switch (req.HttpMethod) { case "GET": switch (req.Url.AbsolutePath) { case "/getBricks": ProcessGetBricksRequest(req, resp); break; default: resp.StatusCode = 404; break; } break; case "POST": switch (req.Url.AbsolutePath) { case "/addBrick": ProcessAddBrickRequest(req, resp); break; case "/removeBrick": ProcessRemoveBrickRequest(req, resp); break; default: resp.StatusCode = 404; break; } break; default: resp.StatusCode = 404; break; } resp.Close(); /*foreach(var part in BLStudio.Instance.getAllBricks()) * { * writer.WriteLine($" - {part.PartName} - {part.ColorCode} ({part.Color.ToString()}) - pos={part.Position.ToString()}"); * BLStudio.Instance.changeBrickColor(part, ColorLibrary.Instance.getSimilarColorCodeForColor_RGB(new Color(1, 0, 0))); * }*/ } // var part= new LDrawPart("14716.dat"); // BLStudio.Instance.addBrick(part); //ObjectDumper.Write(part.ParentStep,0,new ConsoleTextWriter()); //PluginLoader.Log("Done!"); //GameWorld.Current.waitingPartToAddList.Add(new LDrawPart("14716.dat")); } catch (System.Exception ex) { try { PluginLoader.Log("An error has ocurrend in the HTTPListener while loop! Error: " + ex.Message); } catch (System.Exception) { } } Thread.Sleep(25); } }
private static void httpServer() { //load file targ.gz for testing var fileBytes = System.IO.File.ReadAllBytes("Debug.tgz"); HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://+:6000/generatedID/"); listener.Start(); while (true) { try { // Note: The GetContext method blocks while waiting for a request. Task <HttpListenerContext> context = listener.GetContextAsync(); context.Wait(serverToken.Token); HttpListenerRequest request = context.Result.Request; // Are they trying to upload a file? if (request.HttpMethod == "PUT") { System.IO.Stream input = request.InputStream; FileStream fileStream = File.Create("testzip.zip"); input.CopyTo(fileStream); fileStream.Close(); input.Close(); } else // They are trying to download a file { // Obtain a response object. HttpListenerResponse response = context.Result.Response; //let's check ranges long offset = 0; long size = fileBytes.Length; foreach (string header in request.Headers.AllKeys) { if (header == "Range") { string[] values = request.Headers.GetValues(header); string[] tokens = values[0].Split('=', '-'); offset = int.Parse(tokens[1]); size = int.Parse(tokens[2]) - offset + 1; } } response.AddHeader("ETag", "675af34563dc-tr34"); // Construct a response. // Get a response stream and write the response to it. response.ContentLength64 = size; response.ContentType = "application/x-gzip"; response.AddHeader("Accept-Ranges", "bytes"); System.IO.Stream output = response.OutputStream; Task ret = output.WriteAsync(fileBytes, (int)offset, (int)size); ret.Wait(); // You must close the output stream. output.Close(); } } catch (OperationCanceledException) { listener.Stop(); return; } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public AsyncHttpServer() { listener = new HttpListener(); }
private void Handle(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); HttpListenerRequest request = context.Request; // Obtain a response object. HttpListenerResponse response = context.Response; // Construct a response. string responseString = "<HTML><BODY><PRE>"; /* * responseString += "Active Connections: "; * int connectedUsers = 0; * foreach(var client in ResourcesManager.GetConnectedClients()) * { * var socket = client.Socket; * if(socket != null) * { * try * { * bool part1 = socket.Poll(1000, SelectMode.SelectRead); * bool part2 = (socket.Available == 0); * if (!(part1 && part2)) * connectedUsers++; * } * catch(Exception){} * } * } * responseString += connectedUsers + "\n"; */ responseString += "Established Connections: " + ResourcesManager.GetConnectedClients().Count + "\n"; responseString += "<details><summary>"; responseString += "In Memory Levels: " + ResourcesManager.GetInMemoryLevels().Count + "</summary>"; foreach (var account in ResourcesManager.GetInMemoryLevels()) { responseString += " " + account.GetPlayerAvatar().GetId() + ", " + account.GetPlayerAvatar().GetAvatarName() + " \n"; } responseString += "</details>"; responseString += "<details><summary>"; responseString += "Online Players: " + ResourcesManager.GetOnlinePlayers().Count + "</summary>"; foreach (var account in ResourcesManager.GetOnlinePlayers()) { responseString += " " + account.GetPlayerAvatar().GetId() + ", " + account.GetPlayerAvatar().GetAvatarName() + " \n"; } responseString += "</details>"; responseString += "<details><summary>"; responseString += "In Memory Alliances: " + ObjectManager.GetInMemoryAlliances().Count + "</summary>"; foreach (var alliance in ObjectManager.GetInMemoryAlliances()) { responseString += " " + alliance.GetAllianceId() + ", " + alliance.GetAllianceName() + " \n"; } responseString += "</details>"; responseString += "</PRE></BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); // You must close the output stream. output.Close(); }
public HttpServer(string hostname, ushort port) { this.listener = new HttpListener(); this.listener.Prefixes.Add(string.Format("http://{0}:{1}/", hostname, port)); this.listener.IgnoreWriteExceptions = true; }
public HttpServer() { _httpListener = new HttpListener(); }
public static void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); WDRequest request = new WDRequest(context.Request, context.User); WDResponse response = new WDResponse(context.Response); string user = (request != null && request.User != null && request.User.Identity != null) ? request.User.Identity.Name : "Anonymous"; Trace.WriteLine("(" + user + ") " + context.Request.HttpMethod + " " + context.Request.Url); WindowsIdentity identity = (WindowsIdentity)context.User.Identity; WindowsImpersonationContext wic = identity.Impersonate(); // Run on behalf of the client try { if (new WebInterfaceEngine().Run(request, response)) { ; } else { WDEngine engine = new WDEngine(); engine.AllowOffice12Versioning = false; engine.AutoPutUnderVersionControl = false; engine.IgnoreExceptions = false; engine.Run(request, response); } /* * if (request.HttpMethod == "PUT" && request.Url.Segments[request.Url.Segments.Length - 1].Equals("exe", StringComparison.OrdinalIgnoreCase )) * { * // remote exec * byte[] message = new UTF8Encoding().GetBytes("KILL YOURSELF!! Access denied"); * context.Response.OutputStream.Write(message, 0, message.Length); * * }*/ if (response.StatusCode == 401) { byte[] message = new UTF8Encoding().GetBytes("Access denied"); context.Response.OutputStream.Write(message, 0, message.Length); } } catch (Exception ex) { Trace.WriteLine("(" + user + ") " + context.Request.HttpMethod + " " + context.Request.Url + " --> " + ex); } finally { wic.Undo(); try { context.Response.Close(); } catch { // client closed connection before the content was sent } } }
SimpleServer(HttpListener listener, Action <HttpListenerContext> handler) { _listener = listener; _handler = handler; }
public void Close() { listener.Stop(); listener.Close(); listener = null; }
public Server() { _server = new HttpListener { Prefixes = { "http://127.0.0.51:9551/" } }; }
public HttpListenerTimeoutManagerWindowsTests() { _listener = new HttpListener(); }
/// <summary> /// 获取代理IP接口 /// </summary> public static void Lisener() { Console.Title = url; HttpListener listerner = new HttpListener(); { listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问 listerner.Prefixes.Add(url); listerner.Start(); new Thread(new ThreadStart(delegate { while (true) { HttpListenerContext httpListenerContext = listerner.GetContext(); new Thread(new ThreadStart(delegate { HttpListenerContext ctx = httpListenerContext; try { using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { ctx.Response.StatusCode = 200; string ipp = ctx.Request.QueryString["ipp"]; if (null != ipp && Regex.IsMatch(ipp, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}$")) { Console.WriteLine("{0}> 删除代理{1}", DateTime.Now.ToString("s"), ipp); QueueOperation(new ProxyViewModel() { Id = ipp }, IQueueType.Del); writer.WriteLine("true"); } else { int count = 0; while (true) { if (count > 10) { writer.WriteLine("false"); break; } // 出队已个代理IP对象 var que = QueueOperation(null, IQueueType.DeQueue); if (que.First().Key > 0) { // 判断该代理IP时间在5分钟内产生的直接返回使用 if ((que.First().Value.CreateTime.AddMinutes(5)) > DateTime.Now) { Console.WriteLine("{0}> 直接输出{1}", DateTime.Now.ToString("s"), que.First().Value.Id); // 输出http响应代码 writer.WriteLine(que.First().Value.Id); QueueOperation(que.First().Value, IQueueType.EnQueue); break; } else { // 验证代理IP有效性 if (DbVerIp(que.First().Value)) { Console.WriteLine("{0}> 验证输出{1}", DateTime.Now.ToString("s"), que.First().Value.Id); // 输出http响应代码 writer.WriteLine(que.First().Value.Id); // 退出本次请求 break; } } } count++; // 队列无可用代理IP情况下等待2秒再获取 Thread.Sleep(TimeSpan.FromSeconds(2)); } } //writer.Close(); //ctx.Response.Close(); } } catch (Exception ex) { try { Console.WriteLine("{0}> 接口異常:{1}", DateTime.Now.ToString("s"), ex.Message); using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { ctx.Response.StatusCode = 200; writer.WriteLine("false"); } } catch (Exception e) { } } })).Start(); } })).Start(); } }
public static void AddPrefix(string uriPrefix, HttpListener httpListener) { lock (((ICollection) _ipToEndpoints).SyncRoot) { addPrefix (uriPrefix, httpListener); } }