Exemplo n.º 1
1
    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;
            }
        }
    }
Exemplo n.º 2
0
        private void stopToolStripMenuItem_Click(Object sender, EventArgs e)
        {
            listener?.Stop();
            listener?.Close();

            stopToolStripMenuItem.Enabled  = false;
            startToolStripMenuItem.Enabled = true;
        }
Exemplo n.º 3
0
 public void Dispose()
 {
     try
     {
         _listener?.Close();
         _serverThread?.Dispose();
     }
     catch { }
 }
Exemplo n.º 4
0
        public static async Task <string> Authorize(params string[] scopes)
        {
            // Make sure we close before we try again
            listener?.Close();
            listener = new HttpListener();
            listener.Prefixes.Add($"http://localhost:{Port}/");
            listener.Start();

            string scopeStr = string.Join(" ", scopes);

            Process.Start(
                $"https://id.twitch.tv/oauth2/authorize?client_id={ClientID}" +
                $"&redirect_uri=http%3A%2F%2Flocalhost%3A{Port}" +
                $"&response_type=token" +
                $"&scope={scopeStr}");

            while (listener.IsListening)
            {
                var context = await listener.GetContextAsync();

                var request = context.Request;
                if (request.HttpMethod == "POST")
                {
                    string text;
                    using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
                    {
                        text = await reader.ReadToEndAsync();
                    }
                    listener.Close();

                    var keyValuePairs = HttpUtility.UrlDecode(text)
                                        .Split('&')
                                        .Select(kv => kv.Split('='))
                                        .ToDictionary(kv => kv[0].Replace("#", ""), kv => kv[1]);
                    if (keyValuePairs.TryGetValue("access_token", out var accessToken))
                    {
                        return(accessToken);
                    }
                }
                else
                {
                    var    response = context.Response;
                    byte[] buffer   = Encoding.UTF8.GetBytes(HttpRedirect);
                    response.ContentLength64 = buffer.Length;
                    var output = response.OutputStream;
                    await output.WriteAsync(buffer, 0, buffer.Length);

                    output.Close();
                }
            }

            return(null);
        }
Exemplo n.º 5
0
 public void Dispose()
 {
     _httpListener?.Close();
     _httpListener = null;
     (_router as IDisposable)?.Dispose();
     _router = null;
 }
Exemplo n.º 6
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            if (Interlocked.Increment(ref _disposeCount) != 1)
            {
                return;
            }

            Stop();

            lock (_queueStatusProviders)
            {
                while (!_queueStatusProviders.IsEmpty)
                {
                    _queueStatusProviders.TryTake(out _);
                }
            }

            _httpListener?.Close();
            _cancelTokenSource?.Dispose();
        }
Exemplo n.º 7
0
        //public string Wait(string content, CancellationToken token)
        //{
        //    while (!received.Contains(content))//
        //    {
        //        if (token.Stop) return null;
        //        Task.Delay(100).Wait();
        //    }
        //    return received;
        //}

        private void Listen()
        {
            try
            {
                _listener?.Close();
                _listener = new HttpListener();

                _listener.Prefixes.Add("http://localhost:" + _port + "/");
                _listener.Start();
                while (true)
                {
                    if (_stopServer)
                    {
                        _listener.Close();
                        return;
                    }
                    HttpListenerContext context = _listener.GetContext();
                    Process(context);
                }
            }
            catch (Exception ex)
            {
                if (IsStarted)
                {
                    _listener?.Close();
                    Listen();
                }
            }
        }
Exemplo n.º 8
0
        public Task Stop()
        {
            _disposeCancellationTokenSource.Cancel();
            _listener?.Close();

            return(Task.CompletedTask);
        }
Exemplo n.º 9
0
        public void Listen()
        {
            try
            {
                _listener?.Close();
                _listener = new HttpListener();

                _listener.Prefixes.Add("http://*:" + _port + "/");
                _listener.Start();
                while (true)
                {
                    if (_stopServer)
                    {
                        _listener.Close();
                        return;
                    }
                    HttpListenerContext context = _listener.GetContext();
                    Process(context);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                if (IsStarted)
                {
                    _listener?.Close();
                    Listen();
                }
            }
        }
Exemplo n.º 10
0
        protected override void Dispose(bool isDisposing)
        {
            if (_isDisposed)
            {
                return;
            }

            if (isDisposing)
            {
                CloseAsync().GetAwaiter().GetResult();
                _webSocket?.Dispose();
                _httpListener?.Close();
            }

            _isDisposed = true;
        }
Exemplo n.º 11
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _httpListener?.Stop();
         _httpListener?.Close();
     }
 }
Exemplo n.º 12
0
 public void Stop()
 {
     Listener?.Close();
     Listener?.Stop();
     Listener  = null;
     isStarted = false;
     AirportStatUtils.AirportStatsLogger(Log.FromPool("Listener Stopped").WithCodepoint());
 }
Exemplo n.º 13
0
 public void Close()
 {
     clientWaitDisposable?.Dispose();
     httpListener?.Close();
     clientDisposables.ForEach(x => x.Dispose());
     clientDisposables.Clear();
     clients.ForEach(x => x.Dispose());
     clients.Clear();
 }
Exemplo n.º 14
0
 /// <summary>
 /// Stops listening for incoming connections.
 /// </summary>
 public void StopListening()
 {
     Listening = false;
     ReleaseClients();
     httpListener?.Stop();
     httpListener?.Close();
     httpListener = null;
     nat?.DeletePortMapAsync(portMap);
 }
Exemplo n.º 15
0
 private static void StopHttpShow()
 {
     try
     {
         httpListener?.Stop();
     }
     catch { }
     httpListener?.Close();
 }
Exemplo n.º 16
0
        public void Dispose()
        {
            Display?.Dispose();
            Display = null;

            webListener?.Stop();
            webListener?.Close();
            webListener = null;
        }
 public void Stop()
 {
     // TODO: thread safety
     _stop = true;
     _listener?.Stop();
     _listener?.Close();
     _handler?.Dispose();
     _listener = null;
     SetStatus(HttpAsyncHostStatus.Initialised);
 }
Exemplo n.º 18
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            _listener?.Close();
            _acceptSemaphore?.Dispose();
        }
Exemplo n.º 19
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                StopAsync().Wait();
                _httpListener?.Close();
                _httpListener = null;
            }

            base.Dispose(disposing);
        }
Exemplo n.º 20
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            _isDisposed = true;

            _httpListener?.Close();
        }
Exemplo n.º 21
0
        /// <summary>
        /// Releases unmanaged and - optionally - managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (disposing && !_disposedValue)
            {
                Logger.Trace($"Disposing {GetType().Name}");
                AsyncContext.Run(() => StopAsync());
                _httpListener?.Close();
                _httpListener = null;
            }

            _disposedValue = true;
        }
Exemplo n.º 22
0
        public void Stop()
        {
            // shutdown
            stop.Set();
            listener?.Close();
            thread?.Join();

            // reset
            stop.Reset();
            listener = null;
            thread   = null;
        }
 public void Disconnect()
 {
     try
     {
         _listener?.Stop();
         _listener?.Close();
     }
     catch (Exception ex)
     {
         Log.Out("Caught exception when disconnecting: {0}", ex.ToString());
     }
 }
Exemplo n.º 24
0
 private static void StartHttpShow()
 {
     try
     {
         httpListener = new HttpListener();
         httpListener.Prefixes.Add("http://127.0.0.1:44100/");
         httpListener.Start();
         httpListener.BeginGetContext(HttpShowServe, null);
     }
     catch
     {
         httpListener?.Close();
     }
 }
Exemplo n.º 25
0
        public void StopMining()
        {
            Program.Print("[INFO] Master instance stopping...");
            m_isOngoing = false;

            NetworkInterface.OnGetMiningParameterStatus -= NetworkInterface_OnGetMiningParameterStatus;
            NetworkInterface.OnNewChallenge             -= NetworkInterface_OnNewChallenge;
            NetworkInterface.OnNewTarget     -= NetworkInterface_OnNewTarget;
            NetworkInterface.OnNewDifficulty -= NetworkInterface_OnNewDifficulty;
            NetworkInterface.OnStopSolvingCurrentChallenge -= NetworkInterface_OnStopSolvingCurrentChallenge;

            m_Listener?.Stop();
            m_Listener?.Close();
        }
Exemplo n.º 26
0
Arquivo: server.cs Projeto: mono/gert
	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 ();
	}
Exemplo n.º 27
0
        internal void Stop()
        {
            Console.WriteLine("TListener - Stop requested");

            if (!Tokenizer.IsCancellationRequested)
            {
                Tokenizer.Cancel();
            }
            if (_listener.IsListening)
            {
                _listener.Stop();
            }
            ClearListeners();
            _listener?.Close();
        }
Exemplo n.º 28
0
 /// <summary>
 /// サーバー停止
 /// </summary>
 public void StopServer()
 {
     try
     {
         listener?.Close();
     }
     catch (Exception e)
     {
         //Do noting
     }
     finally
     {
         thread?.Join();
     }
 }
Exemplo n.º 29
0
        /// <summary>
        /// Stopps the current HTTP server
        /// </summary>
        public void Stop()
        {
            try
            {
                if (_listener?.IsListening ?? false)
                {
                    _listener?.Stop();
                }

                _listener?.Close();
            }
            finally
            {
                acceptconnections = false;
            }
        }
Exemplo n.º 30
0
        private bool disposedValue = false; // To detect redundant calls

        /// <summary>
        /// Disposes the server.
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    httpListener?.Stop();
                    httpListener?.Close();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
 /// <summary>
 /// サーバー停止
 /// </summary>
 private void StopServerInternal()
 {
     Debug.Log("[SEDSS Server] Stop Internal.");
     try
     {
         listener?.Close();
     }
     catch (Exception e)
     {
         //Do noting
     }
     finally
     {
         thread?.Join();
     }
 }
Exemplo n.º 32
0
 public void StopService()
 {
     try
     {
         if (_listener.IsListening)
         {
             _listener?.Stop();
             _listener?.Abort();
             _listener?.Close();
         }
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Exemplo n.º 33
0
        static UrlPrefix()
        {
            // Find a URL prefix that is not in use on this machine *and* uses a port that's not in use.
            // Once we find this prefix, keep a listener on it for the duration of the process, so other processes
            // can't steal it.

            Guid processGuid = Guid.NewGuid();

            for (int port = 1024; port <= IPEndPoint.MaxPort; port++)
            {
                string prefix = $"http://localhost:{port}/{processGuid:N}/";

                var listener = new HttpListener();
                try
                {
                    listener.Prefixes.Add(prefix);
                    listener.Start();

                    s_processPrefixListener = listener;
                    s_processPrefix = prefix;
                    break;
                }
                catch (Exception e)
                {
                    // can't use this prefix
                    listener.Close();

                    // Remember the exception for later
                    s_processPrefixException = e;

                    // If this is not an HttpListenerException, something very wrong has happened, and there's no point
                    // in trying again.
                    if (!(e is HttpListenerException))
                        break;
                }
            }

            // At this point, either we've reserved a prefix, or we've tried everything and failed.  If we failed,
            // we've saved the exception for later.  We'll defer actually *throwing* the exception until a test
            // asks for the prefix, because dealing with a type initialization exception is not nice in xunit.
        }
Exemplo n.º 34
0
Arquivo: server.cs Projeto: mono/gert
	static void Main ()
	{
		HttpListener listener = new HttpListener ();
		listener.Prefixes.Add ("http://*:8081/");
		listener.Start ();

		HttpListenerContext context = listener.GetContext ();

		// Create the response.
		HttpListenerResponse response = context.Response;
		string responseString = "<html><body>hi client</body></html>";
		byte [] buffer = Encoding.UTF8.GetBytes (responseString);
		response.ContentLength64 = buffer.Length;
		System.Threading.Thread.Sleep (3000);
		response.OutputStream.Write (buffer, 0, buffer.Length);
		if (response != null)
			response.Close ();
		listener.Close ();

		string dir = AppDomain.CurrentDomain.BaseDirectory;
		File.Create (Path.Combine (dir, "ok")).Close ();
	}