public void Disposed5 () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; listener.Close (); string [] strs = new string [0]; coll.CopyTo (strs, 0); }
public void Disposed7 () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; coll.Add ("http://127.0.0.1/"); listener.Close (); int items = 0; foreach (string s in coll) { items++; Assert.AreEqual (s, "http://127.0.0.1/"); } Assert.AreEqual (items, 1); }
/// <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 ReplayServer(MFroReplay replay) { this.replay = replay; this.alive = true; try { server = new HttpListener(); server.Prefixes.Add("http://127.0.0.1:" + port + "/observer-mode/rest/consumer/"); server.Start(); } catch { try { AddAddress("http://127.0.0.1:" + port + "/"); } catch { return; } server = new HttpListener(); server.Prefixes.Add("http://127.0.0.1:" + port + "/observer-mode/rest/consumer/"); server.Start(); } new Thread(this.Stopper) { IsBackground = true, Name = "Server Stopper" }.Start(); new Thread(() => { Logger.WriteLine("Starting Spectator Server [ID: {0}]... ".Format(replay.GameId)); try { while (alive) { Handle(server.GetContext()); } } catch { } server.Close(); Logger.WriteLine("Closing Spectator Server"); }) { IsBackground = true, Name = "ServerHandler" }.Start(); var dir = new System.IO.DirectoryInfo(@"C:\Riot Games\League of Legends\RADS\" + @"solutions\lol_game_client_sln\releases\"); var versions = dir.EnumerateDirectories().ToList(); versions.Sort((a, b) => b.Name.CompareTo(a.Name)); ProcessStartInfo info = new ProcessStartInfo(versions[0].FullName + @"\deploy\League of Legends.exe", String.Join(" ", SpectateArgs).Format(replay.MetaData["encryptionKey"], replay.GameId)); info.WorkingDirectory = versions[0].FullName + @"\deploy"; Process.Start(info); }
// Methods protected override Task ExecuteAsync(CancellationToken stoppingToken) { return(Task.Run(() => { // Variables HttpListener httpListener = null; HttpListenerContext httpContext = null; // Execute try { // HttpListener httpListener = new System.Net.HttpListener(); httpListener.Prefixes.Add(@"http://*****:*****@"{amount:500}"); streamWriter.Close(); } httpContext.Response.Close(); } finally { // Dispose Thread.Sleep(1000); httpListener?.Stop(); httpListener?.Close(); } })); }
private bool CheckPort(int? port) { var listener = new HttpListener(); try { listener.Prefixes.Add("http://+:{0}/".FormatFrom(port)); listener.Start(); return true; } catch (Exception ex) { _log.WarnFormat("Failed to access HTTP port {0}: {1}", port, ex.Summary()); return false; } finally { try { listener.Close(); } catch (Exception ex) { _log.WarnFormat("Failed to close HTTP port {0}: {1}", port, ex.Summary()); } } }
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 HttpServer(string baseDirectory) { this.baseDirectory = baseDirectory; var rnd = new Random(); for (int i = 0; i < 100; i++) { int port = rnd.Next(49152, 65536); try { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:" + port + "/"); listener.Start(); this.port = port; listener.BeginGetContext(ListenerCallback, null); return; } catch (Exception x) { listener.Close(); Debug.WriteLine("HttpListener.Start:\n" + x); } } throw new ApplicationException("Failed to start HttpListener"); }
public void BasicRoundTrip() { var serializer = new JsonCommonSerializer(); var server = new HttpListener(); server.Prefixes.Add("http://localhost:20000/"); server.Start(); var serverTransport = server.GenerateTransportSource(); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService<IMyService>(new MyService()); var client = new ClientWebSocket(); client.Options.SetBuffer(8192, 8192); var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface<IMyService>(); client.ConnectAsync(new Uri("ws://localhost:20000/"), CancellationToken.None).Wait(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); client.Dispose(); serverRouter.Dispose(); serverTransport.Dispose(); server.Stop(); server.Close(); }
static void Main(string[] args) { // Create a HTTP listener. HttpListener listener = new HttpListener(); listener.Prefixes.Add(MyEndpoint); listener.Start(); // will abort if port not permitted and not running in Administrator mode. try { ListenerLoop(listener); Console.Write(DateTime.UtcNow + ": Listening at"); foreach (string p in listener.Prefixes) Console.Write(" " + p); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("Exception: Message:" + ex.Message); } finally { listener.Close(); } }
public static void Main(string[] args) { var port = args.Length == 1 ? int.Parse(args [0]) : 8001; var listener = new System.Net.HttpListener(); // for Non Admin rights // netsh http add urlacl url=http://*:8001/api/Effect user=DOMAIN/user listener.Prefixes.Add(string.Format("http://*:{0}/api/Effect/", port)); listener.Start(); ThreadPool.QueueUserWorkItem((o) => { try { Console.WriteLine("Webserver running..."); while (listener.IsListening) { ThreadPool.QueueUserWorkItem((c) => { var ctx = c as HttpListenerContext; try { var contentLength = (int)ctx.Request.ContentLength64; var buffer = new byte[contentLength]; ctx.Request.InputStream.Read(buffer, 0, contentLength); var obj = Encoding.ASCII.GetString(buffer); var d = (Data)JsonConvert.DeserializeObject(obj, typeof(Data)); string error = String.Empty; byte[] buf = RunMGCB(d.Code, d.Platform, out error); var result = JsonConvert.SerializeObject(new Result() { Compiled = buf, Error = error }); ctx.Response.ContentLength64 = result.Length; ctx.Response.OutputStream.Write(Encoding.UTF8.GetBytes(result), 0, result.Length); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // suppress any exceptions finally { // always close the stream ctx.Response.OutputStream.Close(); } }, listener.GetContext()); } } catch { } }); Console.Read(); listener.Stop(); listener.Close(); }
public void Stop() { if (Listener != null) { Listener.Close(); Listener = null; IsStarted = false; } }
public void Stop() { if (!IsRunning) { return; } listener.Close(); listener.Abort(); listener = null; }
private void KillAnyExistingListeners() { if (ActiveListeners.Count != 0) { var staleListener = new HttpListener(); staleListener.Prefixes.Add(ActiveListeners[0]); staleListener.Stop(); staleListener.Close(); ActiveListeners.Clear(); } ActiveListeners.Add(ListenerAddress); }
public void HttpEndpointDoesNotThrowIfPortIsOccupied() { using (var listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/"); listener.Start(); Metric.Config.WithHttpEndpoint("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/"); listener.Close(); } }
static void Main(string[] args) { HttpListener httpListner = new HttpListener(); httpListner.Prefixes.Add("http://*:8080/"); httpListner.Start(); Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use")); Console.ReadKey(); httpListner.Close(); }
static void Main(string[] args) { Threads(); System.Net.HttpListener listener = new System.Net.HttpListener(); // This doesn't seem to ignore all write exceptions, so in WriteResponse(), we still have a catch block. listener.IgnoreWriteExceptions = true; listener.Prefixes.Add("http://*:8080/"); try { listener.Start(); // Increase the HTTP.SYS backlog queue from the default of 1000 to 65535. // To verify that this works, run `netsh http show servicestate`. Network.Utils.HttpApi.SetRequestQueueLength(listener, 65535); for (;;) { HttpListenerContext context = null; try { context = listener.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(RequestCallback), context); context = null; // ownership has been transferred to RequestCallback } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { if (context != null) { context.Response.Close(); } } } } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { // Stop listening for requests. listener.Close(); Console.WriteLine("Done Listening."); } }
public RequestResult WaitFor(Action request, int timeout) { var result = new RequestResult(); using (var listener = new HttpListener()) { var server = listener; Action test = () => { server.Prefixes.Add(_listenUri); server.Start(); request(); var context = server.GetContext(); result.ContentType = context.Request.ContentType; result.HttpMethod = context.Request.HttpMethod; try { using (var reader = new StreamReader(context.Request.InputStream)) { var body = reader.ReadToEnd(); var serializer = new JavaScriptSerializer(); result.Json = serializer.Deserialize<Dictionary<string, object>>(body); } context.Response.StatusCode = 200; } catch { context.Response.StatusCode = 500; } finally { context.Response.Close(); } }; result.TimedOut = Wait(test, timeout); listener.Stop(); listener.Close(); } return result; }
static void Main(string[] args) { Threads(); System.Net.HttpListener listener = new System.Net.HttpListener(); // This doesn't seem to ignore all write exceptions, so in WriteResponse(), we still have a catch block. listener.IgnoreWriteExceptions = true; listener.Prefixes.Add("http://*:8080/"); try { listener.Start(); for (;;) { HttpListenerContext context = null; try { context = listener.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(RequestCallback), context); context = null; // ownership has been transferred to RequestCallback } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { if (context != null) { context.Response.Close(); } } } } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { // Stop listening for requests. listener.Close(); Console.WriteLine("Done Listening."); } }
protected virtual void Dispose(bool fromDisposeMethod) { if (!_isDisposed) { if (fromDisposeMethod) { if (_listener.IsListening) { StopListening(); } HostManager.UnregisterHost(this); } _listener.Abort(); _listener.Close(); _isDisposed = true; } }
public void HttpEndportLogsAnErrorIfPortIsOccupied() { using (var listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/"); listener.Start(); var loggedAnError = false; using (var config = Metric.Config) { config.WithErrorHandler((exception, s) => { loggedAnError = true; }, true); config.WithErrorHandler((exception) => { loggedAnError = true; }, true); config.WithHttpEndpoint("http://localhost:58888/metricstest/HttpListenerTests/OccupiedPort/"); } Assert.True(loggedAnError); listener.Close(); } }
private string GetNewHttpListenerAddress() { string listenerAddress; while (true) { var listener = new HttpListener(); var randomPortNumber = Random.Next(1025, 65535); listenerAddress = string.Format("http://localhost:{0}/", randomPortNumber); listener.Prefixes.Add(listenerAddress); try { listener.Start(); listener.Stop(); listener.Close(); } catch { continue; } break; } return listenerAddress; }
protected virtual void Dispose(bool fromDisposeMethod) { if (_isDisposed || _listener == null) { return; } if (fromDisposeMethod) { if (_listener.IsListening) { StopListening(); } HostManager.UnregisterHost(this); } _listener.Abort(); _listener.Close(); _isDisposed = true; _zeroPendingRequests.WaitOne(TimeSpan.FromSeconds(5)); }
public void startListner() { stirixListener = stirixSingleton.Instance; stirixListener.Prefixes.Add("http://*:9090/"); stirixListener.Start(); IAsyncResult result; Boolean error=false; while(!error){ try{ result = stirixListener.BeginGetContext(new AsyncCallback(getData), stirixListener); Console.WriteLine("Waiting for request to be processed asyncronously."); } catch(Exception e) { error=true; } } // result.AsyncWaitHandle.WaitOne(); Console.WriteLine("Request processed asyncronously."); stirixListener.Close(); }
public void Listen() { var listener = new System.Net.HttpListener(); listener.Prefixes.Add("http://+:81/"); listener.Start(); do { var context = listener.GetContext(); var request = context.Request; var response = context.Response; if (request.Url.PathAndQuery == "/~close") { response.Close(); break; } var searchInfo = new SearchInfo(); if (request.HttpMethod == "POST" && request.InputStream != null) { searchInfo = _parser.ParseBody(request.InputStream); } else { var dataFromQuery = request.Url.ParseQueryString(); searchInfo = _parser.ParseQuery(dataFromQuery); } var predicate = _filter.BuildExpression(searchInfo); var data = GetData(searchInfo, predicate); var accept = GetAcceptType(request.AcceptTypes); SendResponse(accept, data, response); } while (true); listener.Close(); }
public async Task InitializeAsync(CancellationToken ct) { await TaskUtilities.SwitchToBackgroundThread(); Random r = new Random(); // if remote port is between 10000 and 32000, select a port in the same range. // R Help uses ports in that range. int localPortMin = (RemotePort >= 10000 && RemotePort <= 32000) ? 10000 : 49152; int localPortMax = (RemotePort >= 10000 && RemotePort <= 32000) ? 32000 : 65535; _console.WriteLine(Resources.Info_RemoteWebServerStarting.FormatInvariant(_name)); while (true) { ct.ThrowIfCancellationRequested(); _listener = new HttpListener(); LocalPort = r.Next(localPortMin, localPortMax); _listener.Prefixes.Add(Invariant($"http://{LocalHost}:{LocalPort}/")); try { _listener.Start(); } catch (HttpListenerException) { _listener.Close(); continue; } catch (ObjectDisposedException) { // Socket got closed await Log.WriteLineAsync(LogVerbosity.Minimal, MessageCategory.Error, Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name)); _console.WriteLine(Resources.Error_RemoteWebServerCreationFailed.FormatInvariant(_name)); throw new OperationCanceledException(); } break; } try { await Log.WriteLineAsync(LogVerbosity.Minimal, MessageCategory.General, Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort)); _console.WriteLine(Resources.Info_RemoteWebServerStarted.FormatInvariant(_name, LocalHost, LocalPort)); _console.WriteLine(Resources.Info_RemoteWebServerDetails.FormatInvariant(Environment.MachineName, LocalHost, LocalPort, _name, RemoteHost, RemotePort)); } catch { } }
static void Main(string[] args) { prefix = String.Format("{0}://{1}:{2}/", protocol, serverIP, port); listener = new HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); Console.WriteLine("Server runned {0}", prefix); Console.WriteLine("============"); isListening = true; while (isListening) { if (debug) { Console.WriteLine(); Console.WriteLine("Main logical point"); Console.WriteLine("====="); } try { ThreadPool.QueueUserWorkItem(ProcessRequest, listener.GetContext()); } catch { } } isListening = false; listener.Stop(); listener.Close(); MsSQL.Instance.CloseConnection(); }
static void Main1(string[] args) { System.Configuration.Install.InstallContext _args = new System.Configuration.Install.InstallContext(null, args); if (_args.IsParameterTrue("debug")) { System.Console.WriteLine("Wait for debugger, press any key to continue..."); System.Console.ReadKey(); } System.Net.HttpListener listener = new System.Net.HttpListener(); listener.Prefixes.Add("http://+:80/"); listener.Start(); listener.BeginGetContext(new AsyncCallback(httpListenerCallback), listener); bool quit = false; System.Console.WriteLine("Http starts, press x to terminate..."); while (!quit) { if (System.Console.KeyAvailable) { System.ConsoleKeyInfo k = System.Console.ReadKey(); if (k.KeyChar == 'x') { quit = true; } } if (!quit) { System.Threading.Thread.Sleep(1000); } } if (listener.IsListening) { listener.Stop(); } listener.Close(); }
public static void RunServer() { var prefix = "http://*:" + port +"/"; HttpListener listener = new HttpListener(); listener.Prefixes.Add(prefix); try { Console.WriteLine("Going to listen for print requests at->" + prefix + "..."); listener.Start(); } catch (HttpListenerException hlex) { Console.WriteLine("ERROR:" + hlex.ToString()); System.Environment.Exit(1); return; } while (listener.IsListening) { var context = listener.GetContext(); ProcessRequest(context); } listener.Close(); }
public void Setup() { prefix = ExpHelper.EvalToString(Parser, PrefixExpression); listener = new System.Net.HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); triggerThread = new Thread(() => { while (!isShutingDown) { try { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; // Obtain a response object. HttpListenerResponse response = context.Response; // Construct a response. string responseString = "OK"; 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(); Parser.ParsingContext.Parameters["HLQuerystring"].ParameterValue = request.RawUrl; OnTriggerEvent.Invoke(); } catch { } } listener.Close(); }); triggerThread.Start(); }
public void Disposed4 () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; listener.Close (); coll.Remove ("http://localhost:7777/hola/"); }
public void Disposed3 () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; listener.Close (); coll.Clear (); }
public void Disposed1 () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; listener.Close (); Assert.AreEqual (0, coll.Count, "Count"); Assert.IsFalse (coll.IsReadOnly, "IsReadOnly"); Assert.IsFalse (coll.IsSynchronized, "IsSynchronized"); }
public void CloseWhileBegin () { HttpListener listener = new HttpListener (); listener.Prefixes.Add ("http://127.0.0.1:9001/closewhilebegin/"); listener.Start (); CallMe cm = new CallMe (); listener.BeginGetContext (cm.Callback, listener); listener.Close (); if (false == cm.Event.WaitOne (3000, false)) Assert.Fail ("This should not time out."); Assert.IsNotNull (cm.Error); Assert.AreEqual (typeof (ObjectDisposedException), cm.Error.GetType (), "Exception type"); cm.Dispose (); }
private void ProcessRequests(string[] prefixes) { // Tell user server is starting tsslblWebServer.Text = "Web server: Starting..."; if (!System.Net.HttpListener.IsSupported) { Debug.WriteLine("Windows XP SP2 or higher required."); return; } if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } foreach (string s in prefixes) { listener.Prefixes.Add(s); } try { listener.Start(); Debug.WriteLine(""); Debug.WriteLine("Listening..."); // Tell user server is starting tsslblWebServer.Text = "Web server: OK"; for (int i = 0; i <= 2; i += 0) { HttpListenerResponse response = null; try { HttpListenerContext context = listener.GetContext(); string inURL = context.Request.RawUrl; string responseString = ""; response = context.Response; if (!pageRedirect) { // Send user the html page. responseString = getResponseText(); } else { // Redirect user to the selected page instead. responseString = "<html><head><meta http-equiv=\"Refresh\" content=\"0;url = " + pageRedirectURL + "\"></head></html>"; } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); } catch (HttpListenerException ex) { Debug.WriteLine(ex.Message); } finally { if (response != null) { response.Close(); } } } } catch (HttpListenerException ex) { Debug.WriteLine(ex.Message); } finally { listener.Close(); Debug.WriteLine("Done Listening..."); } }
public void Dispose() { hListener.Close(); }
public void Close() { _httpListener.Close(); }
public void Stop( ) { listener.Stop( ); listener.Close( ); }
public void Close() { _context = null; _httpListener?.Close(); }
public void Close() { _listener.Close(); }
public void FastHttpDispatcherThread() { while (!fastServiceRunning) { try { Environment.Instance.DebugIf("all", "Attempt to start fast service on port '" + fastLocalPort + "'"); fastListener = new HttpListener(); Environment.AuthorizeAddress(fastLocalPort, "Everyone"); fastListener.Prefixes.Add(string.Format("http://*:{0}/", fastLocalPort)); fastListener.Start(); Environment.Instance.DebugIf("all", "Fast XMLRPC Listening on port " + fastLocalPort); fastServiceRunning = true; } catch (HttpListenerException ex) { if (ex.ErrorCode == 5) { DebugError("Permission denied to open socket.\nPlease run this program in Administrator mode."); return; } else { fastLocalPort++; Debug("Fast Port unavaliable." + ex.Message + ", " + ex.InnerException); fastServiceRunning = false; } } } //NotifyClientInfoChanged(""); while (!shutdown) { try { HttpListenerContext context = fastListener.GetContext (); lock (fastHttpRequestsQueue) { fastHttpRequestsQueue.Add (context); } } catch (Exception e) { if (!e.Message.Contains("thread exit")) DebugException (e); fastServiceRunning = false; if (fastListener != null) fastListener.Close (); } } Debug("Terminated FastHttpDispatcherThread"); fastListener.Close(); }
/// <summary> /// Starts the http server. Internally, one async task is used for all requests. /// </summary> public void Start() { if (_isRunning) return; if (!HttpListener.IsSupported) { Console.WriteLine("ERROR! Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return; } if (_prefix == null) { Console.WriteLine("ERROR! prefix missing"); return; } try { _listener = new HttpListener(); _listener.Prefixes.Add(_prefix); _listener.Start(); _isRunning = true; } catch (HttpListenerException ex) { Console.WriteLine("ERROR! http listener at {0} could not be started", _prefix); Console.WriteLine("make sure the user has the rights for this port or run as administrator"); Console.WriteLine(ex); _isRunning = false; } if (_isRunning) { Console.WriteLine("started at " + _prefix); Task.Factory.StartNew(() => { while (!_isStopping) { var context = _listener.GetContext(); var request = context.Request; var response = context.Response; //Console.WriteLine("KeepAlive: {0}", request.KeepAlive); //Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString()); //Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString()); //Console.WriteLine("Is local? {0}", request.IsLocal); //Console.WriteLine("HTTP method: {0}", request.HttpMethod); //Console.WriteLine("Protocol version: {0}", request.ProtocolVersion); //Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated); //Console.WriteLine("Is secure: {0}", request.IsSecureConnection); if (OnReceivedRequest != null) OnReceivedRequest(request, response); } _isRunning = false; _isStopping = false; _listener.Close(); Console.WriteLine("stopped"); if (OnStopped != null) OnStopped(); }); } }
private void OnAuthButtonClicked(object sender, EventArgs args) { if (listener != null && listener.IsListening) { listener.Stop(); listener.Close(); } // TODO: Move this if (Auth == null) { Auth = new Api.OAuth(); } string rootUri = Server + "/api/1.0"; try { RootInfo root = RootInfo.GetRoot(rootUri, new Api.AnonymousConnection()); Auth.AuthorizeLocation = root.AuthorizeUrl; Auth.AccessTokenBaseUrl = root.AccessTokenUrl; Auth.RequestTokenBaseUrl = root.RequestTokenUrl; Auth.ConsumerKey = "anyone"; Auth.ConsumerSecret = "anyone"; Auth.Realm = "Snowy"; } catch (Exception e) { Logger.Error("Failed to get Root resource " + rootUri + ". Exception was: " + e.ToString()); authButton.Label = Catalog.GetString("Server not responding. Try again later."); oauth = null; return; } if (!Auth.IsAccessToken) { listener = new HL.HttpListener(); int portToTry = 8000; string callbackUrl = string.Empty; while (!listener.IsListening && portToTry < 9000) { callbackUrl = String.Format("http://localhost:{0}/tomboy-web-sync/", portToTry); try { listener.Prefixes.Add(callbackUrl); } catch (Exception e) { Logger.Error("Exception while trying to add {0} as an HttpListener Prefix", callbackUrl); Logger.Error(e.ToString()); break; } try { listener.Start(); Auth.CallbackUrl = callbackUrl; } catch { listener.Prefixes.Clear(); portToTry++; } } if (!listener.IsListening) { Logger.Error("Unable to start HttpListener on any port between 8000-8999"); authButton.Label = Catalog.GetString("Server not responding. Try again later."); oauth = null; return; } Logger.Debug("Listening on {0} for OAuth callback", callbackUrl); string authUrl = string.Empty; try { authUrl = Auth.GetAuthorizationUrl(); } catch (Exception e) { listener.Stop(); listener.Close(); Logger.Error("Failed to get auth URL from " + Server + ". Exception was: " + e.ToString()); // Translators: The web service supporting Tomboy WebSync is not responding as expected authButton.Label = Catalog.GetString("Server not responding. Try again later."); oauth = null; return; } IAsyncResult result = listener.BeginGetContext(delegate(IAsyncResult localResult) { HL.HttpListenerContext context; try { context = listener.EndGetContext(localResult); } catch (Exception e) { // TODO: Figure out why this error occurs Logger.Error("Error processing OAuth callback. Could be a sign that you pressed the button to reset the connection. Exception details:"); Logger.Error(e.ToString()); return; } // Assuming if we got here user clicked Allow Logger.Debug("Context request uri query section: " + context.Request.Url.Query); // oauth_verifier is required in OAuth 1.0a, not 1.0 var qs = HttpUtility.ParseQueryString(context.Request.Url.Query); if (!String.IsNullOrEmpty(qs ["oauth_verifier"])) { Auth.Verifier = qs ["oauth_verifier"]; } try { if (!Auth.GetAccessAfterAuthorization()) { throw new ApplicationException("Unknown error getting access token"); } Logger.Debug("Successfully authorized web sync"); } catch (Exception e) { listener.Stop(); listener.Close(); Logger.Error("Failed to authorize web sync, with exception:"); Logger.Error(e.ToString()); Gtk.Application.Invoke(delegate { authButton.Label = Catalog.GetString("Authorization Failed, Try Again"); authButton.Sensitive = true; }); oauth = null; return; } string htmlResponse = String.Format(callbackHtmlTemplate, // Translators: Title of web page presented to user after they authorized Tomboy for sync Catalog.GetString("Tomboy Web Authorization Successful"), // Translators: Body of web page presented to user after they authorized Tomboy for sync Catalog.GetString("Please return to the Tomboy Preferences window and press Save to start synchronizing.")); using (var writer = new System.IO.StreamWriter(context.Response.OutputStream)) writer.Write(htmlResponse); listener.Stop(); listener.Close(); if (Auth.IsAccessToken) { Gtk.Application.Invoke(delegate { authButton.Sensitive = false; authButton.Label = Catalog.GetString("Connected. Press Save to start synchronizing"); }); } }, null); Logger.Debug("Launching browser to authorize web sync: " + authUrl); authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)"); try { Services.NativeApplication.OpenUrl(authUrl, Screen); } catch (Exception e) { listener.Stop(); listener.Close(); Logger.Error("Exception opening URL: " + e.Message); // Translators: Sometimes a user's default browser is not set, so we recommend setting it and trying again authButton.Label = Catalog.GetString("Set the default browser and try again"); return; } // Translators: The user must take action in their web browser to continue the authorization process authButton.Label = Catalog.GetString("Authorizing in browser (Press to reset connection)"); } }
public void Dispose() { InnerListener.Close(); }
private void RunHttpServerThread() { this._httpListenThread = new Thread(new ThreadStart(()=> { HttpListener httpListener = new HttpListener(); try { this._httpImplanter.MakeHttpPrefix(httpListener); httpListener.Start(); } catch (Exception var_1_1F) { Logger.Exit("无法启动服务器监听,请检查网络环境。"); } this._httpImplanter.Start(); IAsyncResult asyncResult = null; while (!this._terminated) { while (asyncResult == null || asyncResult.IsCompleted) { asyncResult = httpListener.BeginGetContext(new AsyncCallback(this.ProcessHttpRequest), httpListener); } this._ready = true; Thread.Sleep(10); } httpListener.Stop(); httpListener.Abort(); httpListener.Close(); this._httpImplanter.Stop(); })); this._httpListenThread.IsBackground = true; this._httpListenThread.Start(); }
public void Stop() { lmListener.Stop(); lmListener.Close(); stop = true; }
private static void ProcessRequests(string[] prefixes) { if (!System.Net.HttpListener.IsSupported) { Console.WriteLine( "Windows XP SP2, Server 2003, or higher is required to " + "use the HttpListener class."); return; } // URI prefixes are required, if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } // Create a listener and add the prefixes. System.Net.HttpListener listener = new System.Net.HttpListener(); foreach (string s in prefixes) { listener.Prefixes.Add(s); } try { // Start the listener to begin listening for requests. listener.Start(); Console.WriteLine("Listening..."); // Set the number of requests this application will handle. int numRequestsToBeHandled = 10; for (int i = 0; i < numRequestsToBeHandled; i++) { HttpListenerResponse response = null; try { // Note: GetContext blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); // Create the response. response = context.Response; string responseString = "<HTML><BODY>The time is currently " + DateTime.Now.ToString( DateTimeFormatInfo.CurrentInfo) + "</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { if (response != null) { response.Close(); } } } } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { // Stop listening for requests. listener.Close(); Console.WriteLine("Done Listening."); } }
static void Main(string[] args) { Threads(); System.Net.HttpListener listener = new System.Net.HttpListener(); // This doesn't seem to ignore all write exceptions, so in WriteResponse(), we still have a catch block. listener.IgnoreWriteExceptions = true; listener.Prefixes.Add("http://*:8080/"); try { listener.Start(); for (;;) { HttpListenerContext context = null; try { context = listener.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(RequestCallback), context); context = null; // ownership has been transferred to RequestCallback } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { if (context != null) context.Response.Close(); } } } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { // Stop listening for requests. listener.Close(); Console.WriteLine("Done Listening."); } }
public void RunHttpModule() { var listenAddress = string.Format("http://{0}:{1}{2}", _host, _port, _virtualDir); _listener = new HttpListener(); _listener.Prefixes.Add(listenAddress); _listener.Start(); NodeRoot.CWriteLine("Started listening from " + listenAddress + "."); _fallBackResultMessage = string.Empty; _fallBackResult = false; #if DEBUG_ if (_routingHandler == null) { _fallBackResultMessage += "Missing Routing handler.<br>"; _fallBackResult = true; } if (_renderers.Count == 0) { _fallBackResultMessage += "Missing Renderes.<br>"; _fallBackResult = true; } if (_pathProviders.Count == 0) { _fallBackResultMessage += "Missing Path providers.<br>"; _fallBackResult = true; } #endif while (_running.Value) { var context = _listener.BeginGetContext(ListenerCallback, _listener); context.AsyncWaitHandle.WaitOne(WAIT_INCOMING_MS); } _listener.Close(); _listener = null; }
[Category ("AndroidNotWorking")] // Test suite hangs if the tests runs as part of the entire BCL suite. Works when only this fixture is ran public void UploadFileAsyncContentType () { var serverUri = "http://localhost:13370/"; var filename = Path.GetTempFileName (); HttpListener listener = new HttpListener (); listener.Prefixes.Add (serverUri); listener.Start (); using (var client = new WebClient ()) { client.UploadFileTaskAsync (new Uri (serverUri), filename); var request = listener.GetContext ().Request; var expected = "multipart/form-data; boundary=---------------------"; Assert.AreEqual (expected.Length + 15, request.ContentType.Length); Assert.AreEqual (expected, request.ContentType.Substring (0, expected.Length)); } listener.Close (); }
public void Close() { _CancelGetContext.Cancel(); _HttpListener.Close(); }
public static void Main() { HttpListener listener = new HttpListener(); string secretKey = ""; string response = ""; try { // Listen for incoming data listener.Start(); } catch (HttpListenerException) { return; } while (listener.IsListening) { var context = listener.GetContext(); var body = new StreamReader(context.Request.InputStream).ReadToEnd(); byte[] b = Encoding.UTF8.GetBytes("ACK"); // Return HTTP Status of 200 to BluePay context.Response.StatusCode = 200; context.Response.KeepAlive = false; context.Response.ContentLength64 = b.Length; var output = context.Response.OutputStream; output.Write(b, 0, b.Length); // Get Reponse using (StreamReader reader = new StreamReader(output)) { response = reader.ReadToEnd(); } context.Response.Close(); } listener.Close(); NameValueCollection vals = HttpUtility.ParseQueryString(response); // Parse data into a NVP collection string transID = vals["trans_id"]; string transStatus = vals["trans_stats"]; string transType = vals["trans_type"]; string amount = vals["amount"]; string batchID = vals["batch_id"]; string batchStatus = vals["batch_status"]; string totalCount = vals["total_count"]; string totalAmount = vals["total_amount"]; string batchUploadID = vals["batch_upload_id"]; string rebillID = vals["rebill_id"]; string rebillAmount = vals["rebill_amount"]; string rebillStatus = vals["rebill_status"]; // calculate the expected BP_STAMP string bpStamp = BluePayPayment_BP10Emu.calcTransNotifyTPS(secretKey, vals["trans_id"], vals["trans_stats"], vals["trans_type"], vals["amount"], vals["batch_id"], vals["batch_status"], vals["total_count"], vals["total_amount"], vals["batch_upload_id"], vals["rebill_id"], vals["rebill_amount"], vals["rebill_status"]); // Output data if the expected BP_STAMP matches the actual BP_STAMP if (bpStamp == vals["BP_STAMP"]) { Console.Write("Transaction ID: " + transID); Console.Write("Transaction Status: " + transStatus); Console.Write("Transaction Type: " + transType); Console.Write("Transaction Amount: " + amount); Console.Write("Rebill ID: " + rebillID); Console.Write("Rebill Amount: " + rebillAmount); Console.Write("Rebill Status: " + rebillStatus); } else { Console.Write("ERROR IN RECEIVING DATA FROM BLUEPAY"); } }
public void Disposed6 () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; listener.Close (); string a = null; foreach (string s in coll) { a = s; // just to make the compiler happy } Assert.IsNull (a); }