GetContext() public method

public GetContext ( ) : HttpListenerContext
return HttpListenerContext
Esempio n. 1
0
        protected override void StartRun()
        {
            _listener = new HttpListener();
            #if !UNSAFE
            try
            {
            #endif
                _listener.Prefixes.Add("http://*:" + (Settings.Instance.WebServerPort) + "/");
                try
                {
                    _listener.Start();
                }
                catch (HttpListenerException ex)
                {
            #if WINDOWS
                    if (ex.NativeErrorCode == 5)
                    {
                        Log.Fatal(@"TO GET XG UP AND RUNNING YOU MUST RUN 'netsh http add urlacl url=http://*:5556/ user=%USERDOMAIN%\%USERNAME%' AS ADMINISTRATOR");
                    }
            #endif
                    throw;
                }

                var fileLoader = new FileLoader {Salt = Salt};

                while (_allowRunning)
                {
            #if !UNSAFE
                    try
                    {
            #endif
                        var connection = new BrowserConnection
                        {
                            Context = _listener.GetContext(),
                            Servers = Servers,
                            Files = Files,
                            Searches = Searches,
                            Snapshots = Snapshots,
                            FileLoader = fileLoader,
                            Password = Password,
                            Salt = Salt
                        };

                        connection.Start();
            #if !UNSAFE
                    }
                    catch (HttpListenerException)
                    {
                        // this is ok
                    }
            #endif
                }
            #if !UNSAFE
            }
            catch (HttpListenerException)
            {
                // this is ok
            }
            #endif
        }
        public void Run()
        {
            try
            {
                Trace.WriteLine("Starting Windows VM Service");

                HttpListener listener = new HttpListener();
                listener.Prefixes.Add(ListenerPrefix);
                listener.Start();

                while (true)
                {
                    try
                    {
                        HttpListenerContext ctx = listener.GetContext();
                        RequestHandler handler = new RequestHandler(ctx, mAccountsManager);
                        handler.ProcessRequest();
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteLine("Exception caught: " + ex.Message + "\n" + ex.StackTrace);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("Exception caught @ run: " + e.Message);
            }
        }
Esempio n. 3
0
        public void Start()
        {
            var listener = new System.Net.HttpListener();

            listener.Prefixes.Add("http://localhost:1234/");

            listener.Start();

            var t = new Thread(_ => {
                while (true)
                {
                    var context = listener.GetContext(); // get te context

                    this.ExecutePipe(context);

                    if (context.Request.HttpMethod == "GET")
                    {
                        _gets.GetOrIgnore(context.Request.Url.AbsolutePath)?.Invoke(context.Request, context.Response);
                    }
                    if (context.Request.HttpMethod == "POST")
                    {
                        _posts.GetOrIgnore(context.Request.Url.AbsolutePath)?.Invoke(context.Request, context.Response);
                    }
                }
            });

            t.Start();
        }
Esempio n. 4
0
        private static void Main(string[] args)
        {
            var listener = new System.Net.HttpListener();

            listener.Prefixes.Add("http://localhost:8080/");
            listener.Prefixes.Add("http://127.0.0.1:8080/");

            listener.Start();

            while (true)
            {
                try
                {
                    var context = listener.GetContext(); //Block until a connection comes in
                    context.Response.StatusCode  = 200;
                    context.Response.SendChunked = true;

                    var bytes = Encoding.UTF8.GetBytes("Hue Hue Hue\n");
                    context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                    context.Response.Close();
                }
                catch (Exception)
                {
                    // Client disconnected or some other error - ignored for this example
                }
            }
        }
Esempio n. 5
0
        /// <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);
            }
        }
Esempio n. 6
0
        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();
        }
Esempio n. 7
0
File: test.cs Progetto: mono/gert
		static void Listener ()
		{
			HttpListener listener = new HttpListener ();
			listener.Prefixes.Add ("http://127.0.0.1:8081/");
			listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
			listener.Start ();

			int requestNumber = 0;

			while (true) {
				HttpListenerContext ctx = listener.GetContext ();

				Stream input = ctx.Request.InputStream;
				StreamReader sr = new StreamReader (input, ctx.Request.ContentEncoding);
				sr.ReadToEnd ();

				ctx.Response.ContentLength64 = 0;
				ctx.Response.StatusCode = 204;
				ctx.Response.StatusDescription = "No Content";

				ctx.Response.Close ();

				requestNumber++;
				if (requestNumber == Count)
					break;
			}
		}
Esempio n. 8
0
        private static void Servicio()
        {
            MyExeHost myHost = (MyExeHost)ApplicationHost.CreateApplicationHost(typeof(MyExeHost), "/", Environment.CurrentDirectory + "\\elWeb");

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:8081/");
            listener.Prefixes.Add("http://127.0.0.1:8081/");
            listener.Start();

            while (true)
            {
                try
                {
                    HttpListenerContext ctx = listener.GetContext();
                    string page = ctx.Request.Url.LocalPath.Replace("/", "");
                    string query = ctx.Request.Url.Query.Replace("?", "");

                    StreamWriter sw = new
                      StreamWriter(ctx.Response.OutputStream);
                    myHost.ProcessRequest(page, query, sw);
                    sw.Flush();
                    ctx.Response.Close();
                }
                catch (Exception ex) { }
            }
        }
Esempio n. 9
0
        public static void start(int port, string adress)
        {
            string[] prefixes = {"http://*"+":"+port+"/"};
            if (!HttpListener.IsSupported){
                Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use this program.");
                return;
            }

            HttpListener listener = new HttpListener();
            // Add the prefixes.
            foreach (string s in prefixes){
                listener.Prefixes.Add(s);
            }

            listener.Start();
            Console.WriteLine("Listening...");
            Console.Title = "WebS - Listening on *:"+port;
            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;
                // Construct a response.
                //Console.Write(request.RawUrl);
                if(checkFile("./web"+request.RawUrl) == "E404"){
                    TextHelper.writeInfo("Connection from "+request.RemoteEndPoint+" on "+request.RawUrl);
                    TextHelper.writeErr(request.RemoteEndPoint+" tried to access "+request.RawUrl+" but it doesn't exist! (404)");
                    writeRes(response, "<HTML><BODY>404 NOT FOUND</BODY></HTML>");
                }else{
                    TextHelper.writeInfo("Connection from "+request.RemoteEndPoint+" on "+request.RawUrl);
                    writeRes(response, checkFile("./web"+request.RawUrl));
                }
            }
        }
Esempio n. 10
0
        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);
        }
Esempio n. 11
0
        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();
        }
Esempio n. 12
0
        public void startListener()
        {
            listener = new HttpListener();
            listener.Prefixes.Add(prefix); // プレフィックスの登録

            listener.Start();

            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest req = context.Request;
                HttpListenerResponse res = context.Response;

                Console.WriteLine(req.RawUrl);

                // リクエストされたURLからファイルのパスを求める
                string path = root + req.RawUrl.Replace("/", "\\");

                // ファイルが存在すればレスポンス・ストリームに書き出す
                if (File.Exists(path))
                {
                    byte[] content = File.ReadAllBytes(path);
                    res.OutputStream.Write(content, 0, content.Length);
                }
                res.Close();
            }
        }
Esempio n. 13
0
        public void Start()
        {
            Task.Run(() =>
            {
                _httpListener = new HttpListener();
                _httpListener.Prefixes.Add(@"http://localhost:" +_portNumber +"/");
                _httpListener.Start();
                Console.WriteLine("The Http Transport Service has started...");

                while (!IsStopped)
                {
                    // Wait for the incoming request.
                    HttpListenerContext context = _httpListener.GetContext();
                    HttpListenerRequest request = context.Request;
                    // Obtain a response object.
                    HttpListenerResponse response = context.Response;

                    // Process the POST request to update the Employee object.
                    if (request.HttpMethod == "POST")
                    {
                        UpdateEmployee(request, response);
                    }
                }
            });
        }
Esempio n. 14
0
		static void HttpServer()
		{
			listener = new HttpListener();
			listener.Prefixes.Add("http://*:5000/");
			listener.Start();
			while (true)
			{
				var context = listener.GetContext();
				var request = context.Request;
				var response = context.Response;

				var tw = new StreamWriter(response.OutputStream);

				var path = request.Url.AbsolutePath;
				if (path.StartsWith("/type/"))
				{
					ShowInstancesOf(tw, path.Substring(6));
				}
				else
				{
					Summary(tw);
				}

				tw.Flush();
				response.OutputStream.Close();
			}
		}
        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;
        }
Esempio n. 16
0
        public override void Run()
        {
            Trace.WriteLine("WorkerRole entry point called", "Information");

            HttpListener listener = new HttpListener();

            IPEndPoint inputEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HelloWorldEndpoint"].IPEndpoint;
            string listenerPrefix = string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}/", inputEndPoint.Address, inputEndPoint.Port);

            Trace.WriteLine("Listening to -" + listenerPrefix);

            listener.Prefixes.Add(listenerPrefix);
            listener.Start();

            while (true)
            {
                // Note: The GetContext method blocks while waiting for a request.
                HttpListenerContext context = listener.GetContext();

                // Obtain a response object.
                HttpListenerResponse response = context.Response;

                // Construct a response.
                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);

                //Close the output stream.
                output.Close();
            }
        }
Esempio n. 17
0
		public void GetContext2 ()
		{
			HttpListener listener = new HttpListener ();
			listener.Start ();
			// "Please call AddPrefix () before calling this method"
			listener.GetContext ();
		}
Esempio n. 18
0
        static void Main(string[] args)
        {
            if(args.Length != 1)
            {
                Console.Error.WriteLine("Usage: name port");

                return;
            }

            int port;
            if(!int.TryParse(args[0], out port))
            {
                Console.Error.WriteLine("Invalid port");
                return;
            }

            var listener = new HttpListener();
            listener.Prefixes.Add(string.Format("http://+:{0}/sort/", port));
            listener.Start();

            while(true)
            {
                SolveAsync(listener.GetContext());
            }
        }
Esempio n. 19
0
        public void ShouldConfigure()
        {
            XmlConfigurator.Configure();
            ILog logger = LogManager.GetLogger(typeof(HttpAppenderTests));

            using (var listener = new HttpListener())
            {
                listener.Prefixes.Add("http://localhost:34343/");
                listener.Start();
                try
                {
                    throw new Exception("KABOOM!");
                }
                catch (Exception e)
                {
                    logger.Error("Oh noes!", e);
                }

                var ctx = listener.GetContext();
                using (var reader = new StreamReader(ctx.Request.InputStream))
                {
                    var body = reader.ReadToEnd();
                    Console.WriteLine(body);
                    Assert.IsNotNull(body);
                }
                ctx.Response.Close();
            }
        }
Esempio n. 20
0
        public void Start(int port)
        {
            _listener = _listener ?? InitializeListenerOnPort(port);
            _listener.Start();

            _task = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                while (!_task.IsCancellationRequested)
                {
                    try
                    {
                        var context = _listener.GetContext();
                        ThreadPool.QueueUserWorkItem(_ => HandleContext(context));
                    }
                    catch (HttpListenerException e)
                    {
                        if (e.ErrorCode == GetContextInterrupted)
                        {
                            // The receiver has been stopped. Return.
                            return;
                        }
                        throw;
                    }
                }
            }, _task.Token);
        }
Esempio n. 21
0
 private HttpListenerContext StartWebServer()
 {
     httpListener = new HttpListener();
     httpListener.Prefixes.Add("http://localhost:12345/");
     httpListener.Start();
     return httpListener.GetContext();
 }
Esempio n. 22
0
        static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            string prefix = String.Format("http://*:{0}/", 51000);
            listener.Prefixes.Add(prefix);
            listener.Start();

            string filename = String.Format(@"d:\logs\stats log {0}.txt", DateTime.Now.ToString("HHmm ddmmyyyy"));
            string fullname = String.Format(@"d:\logs\stats log file {0}.txt", DateTime.Now.ToString("HHmm ddmmyyyy"));
            StreamWriter file = new System.IO.StreamWriter(filename);
            StreamWriter full = new System.IO.StreamWriter(fullname);

            Console.WriteLine($"Logging full to: {fullname}");
            Console.WriteLine($"Logging normal to: {filename}");

            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                int buffersize = (int)context.Request.ContentLength64;
                byte[] buffer = new byte[buffersize];

                context.Request.InputStream.Read(buffer, 0, buffersize);

                string request = Encoding.UTF8.GetString(buffer);
                full.WriteLine(request);

                string formatted = Format(request);
                Console.WriteLine(formatted);
                file.WriteLine(formatted);

                // close response and send http status 200
                context.Response.Close();
            }
        }
Esempio n. 23
0
        public static void AddTask(HttpListener listener)
        {
            var context = listener.GetContext();

            tasks.Add(Task.Factory.StartNew(
                () =>
                {
                    var request = context.Request;
                    var stream = request.InputStream;
                    var query = request.Url.Query;
                    var response = context.Response;

                    if (requests.ContainsKey(query))
                        SendResponse(response, requests[query]);
                    else
                    {
                        var regex = new Regex(@".query=.");
                        lock (requests)
                        {
                            if (regex.IsMatch(query))
                                ProcessRequest(response, query);
                        }
                    }
                }
                ));
        }
Esempio n. 24
0
 public void Start()
 {
     if (!started)
     {
         listener = new HttpListener();
         listener.Prefixes.Add(url);
         listener.Start();
         started = true;
         while (true)
         {
             Console.WriteLine("waiting....");
             HttpListenerContext context = listener.GetContext();
             context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(content);
             context.Response.StatusCode = (int) HttpStatusCode.OK;
             using (var stream = context.Response.OutputStream)
             {
                 using (var writer = new StreamWriter(stream))
                 {
                     writer.Write(content);
                 }
             }
             Console.WriteLine("message sent....");
         }
     }
     else
     {
         Console.WriteLine("server already started");
     }
 }
Esempio n. 25
0
        public static void Main(string[] args)
        {
            if (!HttpListener.IsSupported) {
                Console.WriteLine ("HttpListener not available.");
                Environment.Exit (-1);
            }
            var bytecode = ProgramBytecode ();
            if (bytecode == null) {
                Environment.Exit (-1);
            }
            HttpListener hl = new HttpListener ();
            hl.Prefixes.Add ("http://localhost:8080/");
            hl.Start ();
            var requestNo = 1;
            var fsd = new FileSystemDatabase ("db");
            while (hl.IsListening) {
                var ctx = hl.GetContext ();

                Console.WriteLine ("Serving a request ({0} {1}).", requestNo, ctx.Request.Url.AbsolutePath);

                if (ctx.Request.Url.AbsolutePath == "/") {
                    ServeGuessNumberRequest (ctx, fsd);
                } else {
                    ctx.Response.OutputStream.Close ();
                }

                Console.WriteLine ("Served a request ({0}).", requestNo);
                requestNo++;
            }
        }
Esempio n. 26
0
        private static void OpenFakeHttpServer(int port)
        {
            Console.WriteLine($"Openning port {port}");
            int i = 0;
            var li = new HttpListener();
            li.Prefixes.Add($"http://+:{port}/api/");
            li.Start();
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    var ctx = li.GetContext();
                    using (ctx.Response)
                    {
                        ctx.Response.SendChunked = false;
                        ctx.Response.StatusCode = 200;

                        Console.WriteLine($"at {port} Correlation {ctx.Request.Headers["X-CORRELATION"]}");

                        using (var sw = new StreamWriter(ctx.Response.OutputStream))
                        {
                            ++i;
                            var str = $"{i}!!!";
                            ctx.Response.ContentLength64 = str.Length;
                            sw.Write(str);
                        }
                    }
                }
            });
        }
Esempio n. 27
0
 static int Main(string[] args)
 {
     switch (args.Length)
     {
         case 0:
             prefix = "site/";
             break;
         case 1:
             prefix = args[0];
             if (!Directory.Exists(prefix))
             {
                 Console.Error.WriteLine("Directory does not exist: {0}", prefix);
                 return 1;
             }
             break;
         default:
             Console.Error.WriteLine("Usage: {0} prefix", System.Diagnostics.Process.GetCurrentProcess().ProcessName);
             return 1;
     }
     prefix = new DirectoryInfo(prefix).FullName;
     HttpListener listener = new HttpListener();
     listener.Prefixes.Add("http://*:80/");
     listener.Prefixes.Add("http://*:8080/");
     listener.Start();
     while (listener.IsListening)
     {
         ThreadPool.QueueUserWorkItem(Respond, listener.GetContext());
     }
     return 0;
 }
Esempio n. 28
0
        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();
        }
Esempio n. 29
0
		public void ShouldConfigure()
		{
			XmlConfigurator.Configure();
			ILog logger = LogManager.GetLogger(typeof(HttpAppenderTests));

			using (var listener = new HttpListener())
			{
				listener.Prefixes.Add("http://localhost:34343/");
				listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
				listener.Start();

				try
				{
					throw new Exception("KABOOM!");
				}
				catch (Exception e)
				{
					logger.Error("Oh noes!", e);
				}

				var ctx = listener.GetContext();
				using (var reader = new StreamReader(ctx.Request.InputStream))
				{
					var body = reader.ReadToEnd();
					Console.WriteLine(body);
					Assert.IsNotNull(body);

					HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity;
					Assert.AreEqual("derp", identity.Name);
					Assert.AreEqual("darp", identity.Password);
				}
				ctx.Response.Close();
			}
		}
Esempio n. 30
0
        // initialize git repo as follow
        // > mkdir repository
        // > cd repository
        // > git init .
        // > git config receive.denyCurrentBranch ignore
        static void Main(string[] args)
        {
            if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.Unix)
            {
                GitExe = "/usr/bin/git";
            }

            try
            {
                RepositoryPath = args[0];
                var port = Int32.Parse(args[1]);
                string prefix = String.Format("http://localhost:{0}/", port);
                var listener = new HttpListener();
                listener.Prefixes.Add(prefix);
                listener.Start();
                Console.WriteLine("Listening at " + prefix);
                while (true)
                {
                    // simple handle one request at a time
                    ProcessRequest(listener.GetContext());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 31
0
            // 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();
                    }
                }));
            }
        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();
        }
        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.");
            }
        }
Esempio n. 34
0
 public void Run()
 {
     while (serv.Running)
     {
         try
         {
             Net.HttpListenerContext context = listener.GetContext();
             ThreadPool.QueueUserWorkItem(HandleContext, context);
         }
         catch (Exception)
         {
         }
     }
 }
Esempio n. 35
0
        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.");
            }
        }
Esempio n. 36
0
        private void Listen()
        {
            _listener = new System.Net.HttpListener();
            _listener.Prefixes.Add("http://*:" + _port.ToString() + "/");
            _listener.Start();

            while (true)
            {
                try
                {
                    System.Net.HttpListenerContext context = _listener.GetContext();
                    Process(context);
                }
                catch (Exception ex)
                {
                }
            }
        }
Esempio n. 37
0
        /// <summary>
        /// <![CDATA[异步方法]]>
        /// </summary>
        /// <param name="httpListener"></param>
        /// <returns></returns>
        private void Handle(System.Net.HttpListener httpListener)
        {
            while (true)
            {
                HttpListenerContext context = httpListener.GetContext();
                HttpListenerRequest request = context.Request;
                context.Response.Headers["Server"] = "DTK-Server";
                if (httpListener.IsListening && request != null)
                {
                    HttpListenerResponse response = context.Response;
                    Console.WriteLine("#处理线程{0} 请求ULR:{1}", System.Threading.Thread.CurrentThread.ManagedThreadId, request.Url);

                    string responseString = "This is HttpListener Service!";//默认输出文本
                    response.KeepAlive       = true;
                    response.ContentEncoding = System.Text.Encoding.UTF8;
                    try
                    {
                        WriteJson(response, 200, responseString);//默认输出
                    }
                    catch (ArgumentNullException ex)
                    {
                        WriteJson(response, 0, ex.Message);
                        Console.WriteLine("{0}", ex.Message);
                        continue;
                    }
                    catch (InvalidOperationException ex)
                    {
                        WriteJson(response, 0, ex.Message);
                        Console.WriteLine("{0}", ex.Message);
                        continue;
                    }
                    catch (Exception ex)
                    {
                        WriteJson(response, 0, ex.Message);
                        Console.WriteLine("{0}", ex.Message);
                        continue;
                    }
                    finally
                    {
                    }
                }
            }
        }
Esempio n. 38
0
        public void HTTPSessionThread()
        {
            while (true)
            {
                try
                {
                    // 以HttpListener類別的GetContext方法等待傳入之用戶端請求
                    httpContext = httpListener.GetContext();

                    // Set Thread for each HTTP client Connection
                    Thread clientThread = new Thread(new ThreadStart(this.processRequest));
                    clientThread.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }
Esempio n. 39
0
        void InternalStart(IPAddress addr, int port)
        {
            var context = _Listener.GetContext();

            //context.Request.
            if (addr == null)
            {
                var hostname = Dns.GetHostName();
                var addrs    = System.Net.Dns.GetHostAddresses(hostname);
                foreach (var ad in addrs)
                {
                    if (ad.GetAddressBytes().Length == 4)
                    {
                        addr = ad;
                        break;
                    }
                }
            }
            if (addr == null)
            {
                throw new InvalidProgramException("Cannot bind ipaddress.");
            }
            this.Logger.Log(LogLevels.Information, "Address:" + addr.ToString());
            if (port == 0)
            {
                port = 8080;
            }
            this.Logger.Log(LogLevels.Information, "Port:" + port.ToString());
            var endpoint = new IPEndPoint(addr, port);

            this._ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this._ListenSocket.Bind(endpoint);
            this.Logger.Log(LogLevels.Information, "Bind:" + endpoint.ToString());
            this._ListenSocket.Listen(this.Backlog == 0?5:this.Backlog);
            this.Logger.Log(LogLevels.Information, "Start Listen");

            while (true)
            {
                this._ListenSocket.AcceptAsync(this.AquireAcceptSocketAsyncEventArgs());
            }
        }
Esempio n. 40
0
        public void RunSync()
        {
            try
            {
                _listener = new System.Net.HttpListener();
                _listener.Prefixes.Add(string.Format("http://+:{0}/{1}", Port, Prefix));
                _listener.Start();

                while (true)
                {
                    HttpListenerContext ctx = _listener.GetContext();
                    if (ctx != null)
                    {
                        System.Threading.ThreadPool.QueueUserWorkItem(p =>
                                                                      ProcessRequest(ctx)
                                                                      );
                    }
                }
            }
            catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
        }
Esempio n. 41
0
        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();
        }
Esempio n. 42
0
 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();
 }
Esempio n. 43
0
        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.");
            }
        }
Esempio n. 44
0
 public HttpListenerContext GetContext()
 {
     return(InnerListener.GetContext());
 }
Esempio n. 45
0
        public void  Start()
        {
            int iCount = 0;


            lmListener = new HttpListener();

            string pxUrl = pxc.serverR.proxyUrl;

            if (!pxUrl.EndsWith(@"/"))
            {
                pxUrl += @"/";
            }

            lmListener.Prefixes.Add(pxUrl);

            //netsh http add urlacl url=http://lawmate.secure:8008/lmrasT user=HQ\cweekes --listen=true
            lmListener.Start();

            while (!stop)
            {
                HttpListenerContext context = lmListener.GetContext();
                try
                {
                    iCount++;
                    HttpListenerRequest request = context.Request;

                    Uri url = request.Url;
                    System.Diagnostics.Trace.WriteLine(String.Format("{2}, {0}, {1}", DateTime.Now, url.ToString(), iCount.ToString()));

                    Uri server = new Uri(url.AbsoluteUri.Replace(pxc.serverR.proxyUrl, pxc.serverR.remoteUrl));

                    //  System.Diagnostics.Trace.WriteLine(server.AbsoluteUri);

                    HttpWebRequest wc = (HttpWebRequest)WebRequest.Create(server);
                    wc.Credentials     = cc;
                    wc.PreAuthenticate = true;
                    wc.UnsafeAuthenticatedConnectionSharing = true;
                    wc.Timeout = 0;

                    wc.ContentLength             = request.ContentLength64;
                    wc.CookieContainer           = jar;
                    wc.Method                    = request.HttpMethod;
                    wc.AllowWriteStreamBuffering = false;//for large files

                    wc.ContentType = "application/octet-stream";

                    if (wc.Method == "POST")
                    {
                        Stream toServer = wc.GetRequestStream();

                        Stream fromClient = request.InputStream;

                        RelayStream(fromClient, toServer);
                    }

                    HttpWebResponse hw = (HttpWebResponse)wc.GetResponse();

                    HttpListenerResponse response = context.Response;

                    Stream fromServer = hw.GetResponseStream();
                    Stream output     = response.OutputStream;

                    RelayStream(fromServer, output);
                    hw.Close();
                    output.Close();
                }
                catch (WebException x)
                {
                    HttpListenerResponse response = context.Response;
                    HttpWebResponse      err      = (HttpWebResponse)x.Response;
                    response.StatusCode        = (int)err.StatusCode;
                    response.StatusDescription = err.StatusDescription;

                    Stream fromServer = err.GetResponseStream();
                    Stream output     = response.OutputStream;

                    RelayStream(fromServer, output);
                    err.Close();
                    output.Close();
                }
                catch (Exception xx)
                {
                    System.Diagnostics.Trace.WriteLine(xx.Message);
                }
            }
        }
Esempio n. 46
0
        public HttpContext GetContext()
        {
            HttpListenerContext listenerContext = _listener.GetContext();

            return(new HttpContext(listenerContext, _serializer));
        }
Esempio n. 47
0
        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...");
            }
        }
Esempio n. 48
-1
        private static void Main()
        {
            var listener = new HttpListener();
            const string host = "http://192.168.1.42:9001/";
            listener.Prefixes.Add(host);
            listener.Start();
            Console.WriteLine("Listening on {0}...", host);

            new Thread(() =>
                {
                    Console.ReadLine();
                    Environment.Exit(0);
                }).Start();

            while (true)
            {
                var context = listener.GetContext();
                var response = context.Response;
                var request = context.Request;
                var query = request.QueryString["q"];
                Console.WriteLine("{0} - {1}", DateTime.Now, query);
                var res = "";

                if (query != null)
                {
                    if (Regex.IsMatch(query, "Share")) res = "Point";
                }

                var buffer = Encoding.UTF8.GetBytes(res);
                response.ContentLength64 = buffer.Length;
                var output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                output.Close();
            }
        }
Esempio n. 49
-1
        public void Listen() {
            if (!HttpListener.IsSupported) {
                throw new System.InvalidOperationException(
                    "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!");
            }
            string[] prefixes = new string[] { host };

            listener = new HttpListener();
            foreach (string s in prefixes) {
                listener.Prefixes.Add(s);
            }
            listener.Start();

            while (is_active) {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest request = context.Request;
                Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
                Console.WriteLine("User-Agent: {0}", request.UserAgent);
                Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
                Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" : "close");
                Console.WriteLine("Host: {0}", request.UserHostName);

                HttpListenerResponse response = context.Response;
                if (request.HttpMethod == "GET") {
                    OnGetRequest(request, response);
                } else {
                    OnPostRequest(request, response);
                }
            }
        }