internal void Stop() { try { _listener.Stop(); } catch (ObjectDisposedException) { } }
public void Start() { string[] prefixes = { "http://localhost:8011/" }; if (!HttpListener.IsSupported) { Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return; } // Create a listener. HttpListener listener = new HttpListener(); // Add the prefixes. foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.Start(); Console.WriteLine("Listening..."); int count = 0; while (true) { count++; // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); Router.Current.Route(context.Request, context.Response); } listener.Stop(); }
public async Task<ICredential> AuthenticateAsync(Uri requestUri, Uri callbackUri = null) { var requestUriStrb = new StringBuilder(); requestUriStrb.Append(requestUri.AbsoluteUri); if (callbackUri != null) { requestUriStrb.AppendFormat("&oauth_callback={0}", callbackUri.AbsoluteUri); } var listener = new HttpListener(); listener.Prefixes.Add(callbackUri.AbsoluteUri); listener.Start(); System.Diagnostics.Process.Start(requestUriStrb.ToString()); var ctx = await listener.GetContextAsync(); var token = new Credential(ctx.Request.QueryString.Get("oauth_token"), ctx.Request.QueryString.Get("oauth_verifier")); // empty response // ctx.Response.ContentLength64 = 0; // await ctx.Response.OutputStream.WriteAsync(new byte[0], 0, 0); ctx.Response.OutputStream.Close(); listener.Stop(); return token; }
public void LocalPathWithoutQuery_SpecialCharactersDecodedCorrectly(string urlEnd, string expectedResult) { var listener = new HttpListener(); // Nothing special about 33579. It is a simply a random number we hope is unused. // Note: if you get errors indicating the port is in use, // it is likely the listener.Stop() line below wasn't called somehow. var urlPrefix = "http://localhost:33579/"; listener.Prefixes.Add(urlPrefix); var reqThread = new Thread(() => { Thread.Sleep(100); WebRequest req = WebRequest.Create(urlPrefix + urlEnd); req.GetResponse(); }); reqThread.Start(); try { listener.Start(); var context = listener.GetContext(); // This waits for a request. var requestInfo = new RequestInfo(context); Assert.AreEqual(expectedResult, requestInfo.LocalPathWithoutQuery); } finally { listener.Stop(); reqThread.Join(); } }
// 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(); } })); }
static void Main(string[] args) { listener = new HttpListener(); listener.Prefixes.Add("http://*:" + port + "/"); //add IP of your website to link to gold purchase OR leave blank and create your own hard-coded website! listener.Start(); //Server will freak out if you don't have admin permissions listen = new Thread(ListenerCallback); listen.Start(); for (var i = 0; i < workers.Length; i++) { workers[i] = new Thread(Worker); workers[i].Start(); } Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Terminating..."); listener.Stop(); while (contextQueue.Count > 0) Thread.Sleep(100); Environment.Exit(0); }; Console.ForegroundColor = ConsoleColor.Green; Console.Title = "Database Server"; Console.WriteLine("Connection Successful at Port " + port + "."); XmlDatas.behaviors = false; XmlDatas.DoSomething(); Thread.CurrentThread.Join(); }
//static SemaphoreSlim _semaphore = new SemaphoreSlim(100); public static async Task<Stopwatch> TestAsync() { var server = new HttpListener(); server.Prefixes.Add($"http://{Constants.IpAddress}:{Constants.HttpPort}/"); server.Start(); Console.WriteLine("HTTP-сервер готов."); var stopwatch = new Stopwatch(); var contexts = new List<HttpListenerContext>(); var firstGetContextTask =server.GetContextAsync(); contexts.Add(await firstGetContextTask); Console.WriteLine("Начался HTTP-тест."); stopwatch.Start(); var getContextOtherTasks = Enumerable .Repeat((byte)0, Constants.ClientCount - 1) .Select(_ => { //_semaphore.Wait(); var contextTask = server.GetContextAsync(); //_semaphore.Release(); return contextTask; }); var getContextTasks = new HashSet<Task<HttpListenerContext>> (getContextOtherTasks) { firstGetContextTask }; await ProcessAllAsync(getContextTasks); stopwatch.Stop(); server.Stop(); return stopwatch; }
public 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(); }
private static void Main(string[] args) { HTTPGet req = new HTTPGet(); req.Request("http://checkip.dyndns.org"); string[] a = req.ResponseBody.Split(':'); string a2 = a[1].Substring(1); string[] a3 = a2.Split('<'); string a4 = a3[0]; listener = new HttpListener(); listener.Prefixes.Add("http://*:" + port + "/"); listener.Start(); listen = new Thread(ListenerCallback); listen.Start(); for (int i = 0; i < workers.Length; i++) { workers[i] = new Thread(Worker); workers[i].Start(); } Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Terminating..."); listener.Stop(); while (contextQueue.Count > 0) Thread.Sleep(100); Environment.Exit(0); }; Console.WriteLine("Listening at port " + port + "..."); Console.WriteLine("Server IP: " + a4); Thread.CurrentThread.Join(); }
static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:1234/"); listener.Prefixes.Add("http://127.0.0.1:1234/"); listener.Prefixes.Add("http://192.168.56.102:1234/"); listener.Start(); Console.WriteLine("Listening..."); while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; // Obtain a response object. HttpListenerResponse response = context.Response; string responseString = getCryptoResponse(); byte[] buffer = System.Text.Encoding.Unicode.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(); } listener.Stop(); }
static void Main(string[] args) { listener = new HttpListener(); listener.Prefixes.Add("http://*:" + port + "/"); listener.Start(); listen = new Thread(ListenerCallback); listen.Start(); for (var i = 0; i < workers.Length; i++) { workers[i] = new Thread(Worker); workers[i].Start(); } Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Terminating..."); listener.Stop(); while (contextQueue.Count > 0) Thread.Sleep(100); Environment.Exit(0); }; Console.WriteLine("Listening at port " + port + "..."); XmlDatas.behaviors = false; XmlDatas.DoSomething(); Thread.CurrentThread.Join(); }
static HttpListener listener; // http server providing clipboard history selection public static void Main (string[] args) { // make UI methods for clipboard access available Application.Init (); // setup http interface listener = new HttpListener(); listener.Prefixes.Add("http://*:5544/"); listener.Start(); listener.BeginGetContext(ProcessRequest, null); // initialize access to clipboard clippy = Gtk.Clipboard.Get(Gdk.Atom.Intern("PRIMARY", false)); // schedule polling of clipboard content timer = new System.Timers.Timer(300); timer.Elapsed += new System.Timers.ElapsedEventHandler(ReadClipboardUI); timer.Start(); // just to prevent termination of the app Application.Run(); // shutdown http interface listener.Stop(); }
static void Main(string[] args) { try { dbaddr = db.confreader.getservers(true); listener = new HttpListener(); listener.Prefixes.Add("http://*:" + port + "/"); listener.Start(); listen = new Thread(ListenerCallback); listen.Start(); for (var i = 0; i < workers.Length; i++) { workers[i] = new Thread(Worker); workers[i].Start(); } Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Terminating..."); listener.Stop(); while (contextQueue.Count > 0) Thread.Sleep(100); Environment.Exit(0); }; Console.WriteLine("Listening at port " + port + "..."); Thread.CurrentThread.Join(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.ToString()); Console.ReadLine(); } }
private static ID2LUserContext InterceptUserTokens( HostSpec host, ID2LAppContext appContext ) { // Start HTTP server and listen for the redirect after a successful auth var httpListener = new HttpListener(); httpListener.Prefixes.Add("http://localhost:31337/result/"); httpListener.Start(); // This call blocks until we get a response var ctx = httpListener.GetContext(); // The LMS returns the user tokens via query parameters to the value provided originally in x_target // TODO: deal with "failed to login" case var userContext = appContext.CreateUserContext( ctx.Request.Url, host ); // Send some JavaScript to close the browser popup // This is not 100% effective: for example, Firefox will ignore this. const string RESPONSE = "<!doctype html><meta charset=\"utf-8\"><script>window.close();</script><h1>You may now close your window</h1><p>You may or may not see this message, depending on your browser</p>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes( RESPONSE ); ctx.Response.ContentType = "text/html"; ctx.Response.ContentLength64 = buffer.Length; ctx.Response.OutputStream.Write( buffer, 0, buffer.Length ); ctx.Response.OutputStream.Close(); httpListener.Stop(); return userContext; }
/// <summary> /// Stop the http listener. /// </summary> public void Stop() { // If not running. if (_running) { try { // Stop the service. _running = false; if (_listener != null) { _listener.Stop(); } } catch (Exception) { if (_listener != null) { _listener.Close(); } throw; } } }
static void Main(string[] args) { THNETII.AssemblySplash.WriteAssemblySplash(); Console.WriteLine(); if (args == null || args.Length < 1 || !int.TryParse(args[0], out portNumber)) portNumber = 8899; string host = "+"; if (args != null && args.Length > 1) host = args[1]; nodeGuid = Guid.NewGuid(); Console.CancelKeyPress += OnTerminateSignal; var http_listener = new HttpListener(); http_listener.Prefixes.Add(string.Format("http://{0}:{1}/", host, portNumber)); http_listener.Start(); HandleHttpContext(http_listener); terminateSignal.WaitOne(); ClearConnectionsContext(); http_listener.Stop(); }
static void Main(string[] args) { if (!HttpListener.IsSupported) { Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return; } HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); //listener.Prefixes.Add("http://192.168.1.3:8081/"); listener.Start(); Console.WriteLine("Listening..."); HttpListenerContext context = listener.GetContext(); HttpListenerResponse response = context.Response; HttpListenerRequest request = context.Request; string s = request.RemoteEndPoint.Address.MapToIPv4().ToString(); string responseString = "<HTML><BODY> Hello world!</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(); listener.Stop(); Console.WriteLine("Richiesta da {0}", s); Console.ReadLine(); }
public void Dispose() { if (_listener != null && _listener.IsListening) { _listener.Stop(); } }
public Task<string> HttpListenForOneRequest() { return new Task<string>(() => { var url = ConfigurationManager.AppSettings["httpListenerUrl"]; var listener = new HttpListener(); listener.Prefixes.Add(url); listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; listener.TimeoutManager.IdleConnection = TimeSpan.FromMilliseconds(500); listener.Start(); HttpListenerContext context = listener.GetContextAsync().Result; string requestContent; using (var r = new StreamReader(context.Request.InputStream)) { requestContent = r.ReadToEnd(); } context.Response.StatusCode = 200; context.Response.Close(); listener.Stop(); return requestContent; }); }
public void Stop(HttpListener listener, Task handleRequests, Task updateWorld) { _exiting = true; listener.Stop(); updateWorld.Wait(TimeSpan.FromSeconds(2)); handleRequests.Wait(TimeSpan.FromSeconds(2)); }
/// <summary> /// Запускает сервер, стартует все приложения внутри сервера /// </summary> public void Run() { using (HttpListener listener = new HttpListener ()) { listener.Prefixes.Add (string.Format ("http://{0}:{1}/", _settings.Host, _settings.Port)); foreach (var app in _apps) { string prefix = string.Format ("http://{0}:{1}{2}", _settings.Host, _settings.Port, app.Path); listener.Prefixes.Add (prefix); Logger.Info ("Application added on: '{0}'", prefix); } listener.Start (); Logger.Info ("HTTPListener started at '{0}:{1}'", _settings.Host, _settings.Port); while (!_disposed.WaitOne(TimeSpan.FromMilliseconds(10))) { var context = listener.GetContext(); ProcessRequest(context); } listener.Stop (); Logger.Info ("HTTPListener stopped at '{0}:{1}'", _settings.Host, _settings.Port); } }
private void btnExitStop_Click(object sender, EventArgs e) { iniSave(); listener.Stop(); // Stop background web host listener. bgWorkerThread.Abort(); // Close background web host thread. No data can be lost, so Abort() is fine. exitAndStop = true; // Stops "Are you sure" message. Application.Exit(); }
/// <summary> /// 释放 /// </summary> public void Dispose() { if (listener != null) { listener.Stop(); listener = null; } }
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 start() { try { LogUtil.debug("start http server"); using (HttpListener listerner = new HttpListener()) { listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问18. listerner.Prefixes.Add("http://localhost:8111/web/"); if(listerner.IsListening) listerner.Stop(); listerner.Start(); Console.WriteLine("WebServer Start Successed......."); while (!isStop) { //等待请求连接26. //没有请求则GetContext处于阻塞状态27. HttpListenerContext ctx = listerner.GetContext(); ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码29. string plantId = ctx.Request.QueryString["plantId"]; string plantName = ctx.Request.QueryString["plantName"]; if (plantId != null) { LogUtil.debug("http server accept plantId:" + plantId); } //使用Writer输出http响应代码38. using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { Console.WriteLine("hello"); writer.WriteLine("<html><head><title>The WebServer Test</title></head><body>"); writer.WriteLine("<div style=\"height:20px;color:blue;text-align:center;\"><p> hello {0}</p></div>", plantId); writer.WriteLine("<ul>"); foreach (string header in ctx.Request.Headers.Keys) { writer.WriteLine("<li><b>{0}:</b>{1}</li>", header, ctx.Request.Headers[header]); } writer.WriteLine("</ul>"); writer.WriteLine("</body></html>"); writer.Close(); ctx.Response.Close(); } ControlCenter.pauseTime = DateTime.Now; ControlCenter.isPause = true; LogUtil.debug("manualopen plant:" + plantId); AcceptForm.sendCmdMessage("manualopen-" + plantId);//打开详细页面 } } } catch (Exception ee) { LogUtil.error("start http server error:" + ee.StackTrace); } }
public IDisposable Start() { if (inner != null) { throw new InvalidOperationException("Already started!"); } var server = new HttpListener(); server.Prefixes.Add(String.Format("http://+:{0}/", Port)); server.Start(); bool shouldStop = false; var listener = Task.Run(async () => { while (!shouldStop) { var ctx = await server.GetContextAsync(); if (ctx.Request.HttpMethod != "GET") { closeResponseWith(ctx, 400, "GETs only"); return; } var target = Path.Combine(RootPath, ctx.Request.Url.AbsolutePath.Replace('/', Path.DirectorySeparatorChar).Substring(1)); var fi = new FileInfo(target); if (!fi.FullName.StartsWith(RootPath)) { closeResponseWith(ctx, 401, "Not authorized"); return; } if (!fi.Exists) { closeResponseWith(ctx, 404, "Not found"); return; } try { using (var input = File.OpenRead(target)) { ctx.Response.StatusCode = 200; input.CopyTo(ctx.Response.OutputStream); ctx.Response.Close(); } } catch (Exception ex) { closeResponseWith(ctx, 500, ex.ToString()); } } }); var ret = Disposable.Create(() => { shouldStop = true; server.Stop(); listener.Wait(2000); inner = null; }); inner = ret; return ret; }
public void StopListening() { CheckNotDisposed(); using (new ContextScope(new AmbientContext())) { Stop(this, EventArgs.Empty); } _listener.Stop(); }
public void AddOne () { HttpListener listener = new HttpListener (); HLPC coll = listener.Prefixes; listener.Start (); coll.Add ("http://127.0.0.1:8181/"); Assert.AreEqual (1, coll.Count, "Count"); Assert.IsFalse (coll.IsReadOnly, "IsReadOnly"); Assert.IsFalse (coll.IsSynchronized, "IsSynchronized"); listener.Stop (); }
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 Stop() { if (!_isStarted) { return; } _listener.Stop(); _connections.Clear(); _handlers.Clear(); _isStarted = false; }
public virtual void Stop() { if (_listener != null) { try { _listener.Stop(); _listener = null; } catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; } } }
public IDisposable Start() { if (inner != null) { throw new InvalidOperationException("Already started!"); } var server = new HttpListener(); server.Prefixes.Add(String.Format("http://+:{0}/", Port)); server.Start(); var listener = Observable.Defer(() => Observable.FromAsyncPattern<HttpListenerContext>(server.BeginGetContext, server.EndGetContext)()) .Repeat() .Subscribe(ctx => { if (ctx.Request.HttpMethod != "GET") { closeResponseWith(ctx, 400, "GETs only"); return; } var target = Path.Combine(RootPath, ctx.Request.Url.AbsolutePath.Replace('/', Path.DirectorySeparatorChar).Substring(1)); var fi = new FileInfo(target); if (!fi.FullName.StartsWith(RootPath)) { closeResponseWith(ctx, 401, "Not authorized"); return; } if (!fi.Exists) { closeResponseWith(ctx, 404, "Not found"); return; } try { using (var input = File.OpenRead(target)) { ctx.Response.StatusCode = 200; input.CopyTo(ctx.Response.OutputStream); ctx.Response.Close(); } } catch (Exception ex) { closeResponseWith(ctx, 500, ex.ToString()); } }); var ret = Disposable.Create(() => { listener.Dispose(); server.Stop(); inner = null; }); inner = ret; return ret; }
/// <summary> /// Will create the web server on the specified port. If the port is in use /// a random port number will automatically be used. Callers should always /// verify the port with the BaseUri property. /// </summary> /// <param name="possibleRequests">The relative Uri's this server will handle.</param> /// <param name="port">The port to listen on.</param> public WebServer(Uri[] possibleRequests, int port) { if (possibleRequests == null) { throw new ArgumentNullException("possibleRequests"); } foreach (Uri possible in possibleRequests) { if (possible.IsAbsoluteUri) { throw new ArgumentOutOfRangeException("possibleRequests", "Uris provided must be relative."); } } if ((port < 0) || (port > _maxPort)) { throw new ArgumentOutOfRangeException("port", string.Format("Value must be between 0 and {0}", _maxPort)); } _possibleRequests = possibleRequests; bool foundValidPort = false; while (!foundValidPort) { _baseUri = new Uri(string.Format("{0}://{1}:{2}/Test/", Uri.UriSchemeHttp, _serverIpAddress, port)); _listener = new System.Net.HttpListener(); _listener.Prefixes.Add(_baseUri.OriginalString); try { // triggers port usage and validation _listener.Start(); _listener.Stop(); foundValidPort = true; } catch (HttpListenerException hle) { if (hle.ErrorCode == 32) // Magic Number: PortInUse Error { // generate random port port = new Random().Next(_minRandomPort, _maxPort); } else { throw hle; } } } }
private void Execute() { HttpListener listener = new HttpListener(); listener.IgnoreWriteExceptions = true; listener.Prefixes.Add(String.Format("http://{0}:{1}/", address, port.ToString())); listener.Start(); Console.WriteLine(String.Format("listening port {0}...", port.ToString())); String path = ""; bool terminated = false; while (!terminated) { Console.WriteLine("wait for request.."); HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; try { path = request.Url.LocalPath; Console.WriteLine(path); String action = path.Substring(1, path.Length - 1); String result = ""; if (actions.ContainsKey(action)) { result = actions[action](request.QueryString); } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(result); response.ContentLength64 = buffer.Length; int blockSize = 1024; int i = 0; while (i < buffer.Length) { if (buffer.Length - i < blockSize) blockSize = buffer.Length - i; response.OutputStream.Write(buffer, i, blockSize); i += blockSize; } response.OutputStream.Flush(); response.Close(); } catch { // todo } } listener.Stop(); }
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) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); HttpListenerContext context = listener.GetContext(); byte[] byteArr = Encoding.ASCII.GetBytes("Hello World!"); context.Response.OutputStream.Write(byteArr, 0, byteArr.Length); context.Response.Close(); listener.Stop(); }
public static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:9000/"); listener.Start(); Log("Server started on port 9000!"); new Thread(new ThreadStart(ReadInput)).Start(); new Thread(delegate() { ReadRequest(listener); }).Start(); while (!needStopServer) { } listener.Stop(); Log("Server stopped."); Thread.Sleep(500); }
private static bool ProbeUrl(string url) { try { var listener = new HttpListener(); listener.Prefixes.Add(url); listener.Start(); listener.Stop(); } catch { return false; } return true; }
public static void Main(string[] args) { string path = string.Empty; int port = 1234; if (args.Length > 0) path = args[0]; if (args.Length > 1) int.TryParse(args[1], out port); string hostName = string.Format("http://localhost:{0}/", port); HttpListener listener = new HttpListener(); listener.Prefixes.Add(hostName); listener.Start(); Console.WriteLine("Listening... "); Console.WriteLine("Open {0} in a browser", hostName); while (listener.IsListening) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; Console.WriteLine(request.Url.AbsolutePath); HttpListenerResponse response = context.Response; string filePath = Path.Combine(path, request.Url.AbsolutePath.TrimStart('/')); byte[] buffer; string filetype = string.Empty; if (File.Exists(filePath)) { buffer = File.ReadAllBytes(filePath); filetype = Path.GetExtension(filePath); response.ContentLength64 = buffer.Length; response.ContentType = Mimetypes.GetMimetype(filetype); response.StatusCode = 200; } else { buffer = System.Text.Encoding.UTF8.GetBytes(Page404.Page404Html); response.ContentType = Mimetypes.GetMimetype(".html"); response.StatusCode = 404; } Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); buffer = null; output.Close(); } listener.Stop(); }
private static bool CanStartHttpListener(int port) { try { var httpListener = new HttpListener(); httpListener.Prefixes.Add("http://+:" + port + "/"); httpListener.Start(); httpListener.Stop(); return true; } catch (HttpListenerException e) { if (e.ErrorCode != 5) //access denies throw; } return false; }
public void FireOne() { var listener = new HttpListener(); listener.Prefixes.Add("http://+:8080/"); listener.Start(); var ctx = listener.GetContext(); var request = ctx.Request; var response = ctx.Response; var writer = new StreamWriter(response.OutputStream); writer.WriteLine("A,B,C,D\t10,20,30,40"); writer.Flush(); response.Close(); listener.Stop(); }
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 async Task <string> SignIn() { // create a redirect URI using an available port on the loopback address. //string redirectUri = string.Format("https://app.pollination.cloud/callback"); string redirectUri = string.Format("http://localhost:3000/"); Console.WriteLine("redirect URI: " + redirectUri); Console.WriteLine("-----------------------------------"); // create an HttpListener to listen for requests on that redirect URI. var listener = new System.Net.HttpListener(); listener.Prefixes.Add(redirectUri); Console.WriteLine("Listening.."); listener.Start(); var verifier = GenVerifier(); var codeChallenge = GenCodeChallenge(verifier); //var verifier = state.CodeVerifier; Console.WriteLine("Verifier: " + verifier); Console.WriteLine("-----------------------------------"); var state = GenState(); Console.WriteLine("state: " + state); //var loginURL = state.StartUrl; // Build URL var loginURL = Auth0URL; loginURL += $"authorize?response_type=code"; loginURL += $"&code_challenge={codeChallenge}"; loginURL += $"&code_challenge_method=S256"; loginURL += $"&client_id={Auth0ClientID_GH}"; loginURL += $"&scope=openid"; loginURL += $"&redirect_uri={redirectUri}"; loginURL += $"&state={state}"; Console.WriteLine($"Start login URL: {loginURL}"); var psi = new System.Diagnostics.ProcessStartInfo { FileName = loginURL, UseShellExecute = true }; System.Diagnostics.Process.Start(psi); // wait for the authorization response. var context = await listener.GetContextAsync(); var request = context.Request; var response = context.Response; Console.WriteLine("-----------------------------------"); Console.WriteLine($"AUTHORIZATION_CODE: "); var returnUrl = request.RawUrl.Contains("?code=") ? request.RawUrl : request.UrlReferrer.PathAndQuery; var AUTHORIZATION_CODE = returnUrl.Split('&').FirstOrDefault(_ => _.StartsWith("/?code=")).Split('=').Last().Trim(); //Console.WriteLine(AUTHORIZATION_CODE); Console.WriteLine($"State: "); var returnState = request.RawUrl.Split('&').FirstOrDefault(_ => _.StartsWith("state=")).Split('=').Last().Trim(); //Console.WriteLine(returnState); var IsAuthorized = returnState.Equals(state); IsAuthorized &= !string.IsNullOrEmpty(AUTHORIZATION_CODE); Console.WriteLine($"IsAuthorized: {IsAuthorized}"); Console.WriteLine("-----------------------------------"); var responseMessage = "This is not an authorized request!"; // Request Tokens if (IsAuthorized) { var restClient = new RestClient($"{Auth0URL}oauth/token"); var restRequest = new RestRequest(Method.POST); //restRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded"); restRequest.AddParameter( "application/x-www-form-urlencoded", $"grant_type=authorization_code&client_id={Auth0ClientID_GH}&code_verifier={verifier}&code={AUTHORIZATION_CODE}&redirect_uri={redirectUri}", ParameterType.RequestBody ); var restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { var responseContent = restResponse.Content; var id_token = JsonConvert.DeserializeObject <Newtonsoft.Json.Linq.JObject>(responseContent)["id_token"].ToString(); ID_TOKEN = id_token; Console.WriteLine("Successful login!"); //Console.WriteLine("id_token: " + id_token); Console.WriteLine("-----------------------------------"); responseMessage = "Signed in!. \n\nYou can close this window, and return to the Grasshopper."; } } //sends an HTTP response to the browser. string responseString = string.Format($"<html><head></head><body>{responseMessage}</body></html>"); var buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; await responseOutput.WriteAsync(buffer, 0, buffer.Length); responseOutput.Close(); listener.Stop(); return(ID_TOKEN); }
public void Stop( ) { listener.Stop( ); listener.Close( ); }
public void Stop() { InnerListener.Stop(); }
private static async Task <AuthResult> PollinationSignInAsync(bool devEnv = false) { if (!HttpListener.IsSupported) { Helper.Logger.Error($"PollinationSignInAsync: HttpListener is not supported on this system"); throw new ArgumentException("PollinationSignIn is not supported on this system"); } var redirectUrl = "http://localhost:8645/"; var loginUrl = devEnv ? LoginURL_Dev : LoginURL; var listener = new System.Net.HttpListener(); try { listener.Prefixes.Add(redirectUrl); listener.Start(); //listener.TimeoutManager.IdleConnection = TimeSpan.FromSeconds(30); //listener.TimeoutManager.HeaderWait = TimeSpan.FromSeconds(30); } catch (HttpListenerException e) { //it is already listening the port, but users didn't login if (e.ErrorCode == 183) { Console.WriteLine(e.Message); Helper.Logger.Warning($"PollinationSignInAsync: it is still waiting for users to login from last time.\n{e.Message}"); } else { Helper.Logger.Error($"PollinationSignInAsync: Failed to start the listener.\n{e.Message}"); throw e; } } var psi = new System.Diagnostics.ProcessStartInfo { FileName = loginUrl, UseShellExecute = true }; System.Diagnostics.Process.Start(psi); Helper.Logger.Information($"PollinationSignInAsync: login from {loginUrl}"); // wait for the authorization response. var context = await listener.GetContextAsync(); var request = context.Request; var response = context.Response; var returnUrl = request.RawUrl.Contains("?token=") ? request.RawUrl : request.UrlReferrer?.PathAndQuery; if (string.IsNullOrEmpty(returnUrl)) { Helper.Logger.Error($"PollinationSignInAsync: Failed to authorize the login: \n{request.RawUrl}"); throw new ArgumentException($"Failed to authorize the login: \n{request.RawUrl}"); } //sends an HTTP response to the browser. string responseString = string.Format("<html><head></head><body style=\"text-align: center; font-family: Lato, Helvetica, Arial, sans-serif\"><img src=\"https://app.pollination.cloud/logo.svg\"><h1>Authorization was successful!</h1><p>You can close this browser window.</p></body></html>"); var buffer = Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; await responseOutput.WriteAsync(buffer, 0, buffer.Length); await Task.Delay(1000); responseOutput.Flush(); responseOutput.Close(); listener.Stop(); Helper.Logger.Information($"PollinationSignInAsync: closing the listener"); return(AuthResult.From(request.QueryString)); }
/// <exclude /> public override void Dispose() { mHttpListener.Stop(); }
/// <summary> /// 释放 /// </summary> public void Dispose() { listener.Stop(); listener = null; }
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 async Task <string> InitiateTokenRetrieval() { string state = RandomDataBase64Url(32); string redirectURI = ""; var http = new System.Net.HttpListener(); foreach (var i in new int[] { 17236, 17284, 17287, 17291, 17296 }) { try { redirectURI = string.Format("http://localhost:{0}/", i); http.Prefixes.Add(redirectURI); http.Start(); break; } catch (Exception e) { http = new System.Net.HttpListener(); } } var client = new HttpClient(); string json = await client.GetStringAsync("https://presence-light.azurewebsites.net/api/KeyVault?code=0UGo7xdQmumEzoCV8vRNXv6Z8pGxWvtu7b6a0meOtDlQCB43oxIEfw=="); var secretResponse = JsonConvert.DeserializeObject <List <SecretResponse> >(json); _lifxClientId = secretResponse.FirstOrDefault(a => a.Secret == "LIFXClientId").Value; _lifxClientSecret = secretResponse.FirstOrDefault(a => a.Secret == "LIFXClientSecret").Value; // Creates the OAuth 2.0 authorization request. string authorizationRequest = string.Format("{0}?response_type=code&scope=remote_control:all&client_id={1}&state={2}&redirect_uri={3}", _lIFXAuthorizationEndpoint, _lifxClientId, state, HttpUtility.UrlEncode(redirectURI) ); Helpers.OpenBrowser(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); //Sends an HTTP response to the browser. var response = context.Response; string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://lifx.com'></head><body>Please return to the app.</body></html>"); var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); Debug.WriteLine("HTTP server stopped."); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { return(""); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { return(""); } // extracts the code var code = context.Request.QueryString.Get("code") ?? ""; var incoming_state = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incoming_state != state) { return(""); } // Starts the code exchange at the Token Endpoint. return(await PerformCodeExchange(code)); }
public void Stop() { _listener.Stop(); }
public void Stop() { _httpListener.Stop(); }
public async Task <string> InitiateTokenRetrieval() { try { string state = RandomDataBase64Url(32); string redirectURI = ""; var http = new System.Net.HttpListener(); foreach (var i in new int[] { 17236, 17284, 17287, 17291, 17296 }) { try { redirectURI = string.Format("http://localhost:{0}/", i); http.Prefixes.Add(redirectURI); http.Start(); break; } catch { http = new System.Net.HttpListener(); } } // Creates the OAuth 2.0 authorization request. string authorizationRequest = string.Format("{0}?response_type=code&scope=remote_control:all&client_id={1}&state={2}&redirect_uri={3}", _lIFXAuthorizationEndpoint, _options.LightSettings.LIFX.LIFXClientId, state, HttpUtility.UrlEncode(redirectURI) ); Helpers.OpenBrowser(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync().ConfigureAwait(true); //Sends an HTTP response to the browser. var response = context.Response; string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://lifx.com'></head><body>Please return to the app.</body></html>"); var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); Debug.WriteLine("HTTP server stopped."); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { return(""); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { return(""); } // extracts the code var code = context.Request.QueryString.Get("code") ?? ""; var incoming_state = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incoming_state != state) { return(""); } // Starts the code exchange at the Token Endpoint. return(await PerformCodeExchange(code).ConfigureAwait(true)); } catch (Exception e) { _logger.LogError("Error retrieving LIFX Token", e); throw; } }
public void Stop() { lmListener.Stop(); lmListener.Close(); stop = true; }