Inheritance: IDisposable
Ejemplo n.º 1
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);
            }
        }
Ejemplo n.º 2
0
 public Server(string host, int port, Func<IRequestHandler> handlerFactory)
 {
     _listener = new HttpListener();
     _Binding = string.Format("http://{0}:{1}/", host, port);
     _listener.Prefixes.Add(_Binding);
     _HandlerFactory = handlerFactory;
 }
Ejemplo n.º 3
0
        private void EndGetRequest(IAsyncResult result)
        {
            HttpListenerContext context = null;

            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;

            try
            {
                context = listener.EndGetContext(result);
                using (context.Response)
                    HandleRequest(context);
            }
            catch (Exception ex)
            {
                Console.Write("Exception in listener: {0}{1}", Environment.NewLine, ex);
            }
            finally
            {
                try
                {
                    if (listener.IsListening)
                    {
                        listener.BeginGetContext(EndGetRequest, listener);
                    }
                }
                catch
                {
                    Stop();
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 启动
        /// </summary>
        public async void StartAsync()
        {
            var listener = new System.Net.HttpListener();

            listener.Prefixes.Add($"http://{_endPoint.ToString()}/GarbageBin/Data/");

            // 启动服务器
            try
            {
                listener.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"智慧垃圾桶,启动服务器失败,{ex.ToString()}");
                return;
            }

            // 消息接收
            while (true)
            {
                try
                {
                    var context = await listener.GetContextAsync();

                    var result = await ReceiveMessage(context);
                    await SendResponse(context, result);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"智慧垃圾桶,获取请求失败,{ex.ToString()}");
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Starts the Authorisation listener to listen to the specified port.
        /// </summary>
        /// <param name="port"></param>
        public void ListenTo(int port)
        {
            if (!HttpListener.IsSupported)
            {
                Debug.Write("AuthListener unsupported: Windows XP SP2 or Server 2003 is required");
                throw new NotSupportedException("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
            }

            try
            {
                this._server = new HttpListener();

                var prefix = String.Format("http://localhost:{0}/", port);
                this._server.Prefixes.Add(prefix);
                Debug.WriteLine("Prefix " + prefix + " added.");

                // Start listening for client requests.
                this._server.Start();
                Debug.WriteLine("Waiting for a connection... ");

                // Start waiting for a request
                _server.BeginGetContext(new AsyncCallback(ListenerCallback), _server);
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
                this.Stop();
            }
        }
Ejemplo n.º 6
0
        public static void GetContext(System.Net.HttpListener listener, Action <Exception, System.Net.HttpListenerContext> callback)
        {
            try
            {
                listener.BeginGetContext((result) =>
                {
                    try
                    {
                        var context = listener.EndGetContext(result);

                        Loop.Post(() =>
                        {
                            callback(null, context);
                        });
                    }
                    catch (Exception exception)
                    {
                        Loop.Post(() =>
                        {
                            callback(exception, null);
                        });
                    }
                }, null);
            }
            catch (Exception exception)
            {
                callback(exception, null);
            }
        }
Ejemplo n.º 7
0
		public static HttpListener CreateAndStartListener (string prefix)
		{
			HttpListener listener = new HttpListener ();
			listener.Prefixes.Add (prefix);
			listener.Start ();
			return listener;
		}
Ejemplo n.º 8
0
 /// <summary>
 /// Http监听器
 /// </summary>
 /// <param name="host">监听host</param>
 /// <param name="port">监听端口</param>
 public HttpListener(string host = "*", int port = 9478)
 {
     listener = new Listener();
     listener.Prefixes.Add("http://" + host + ":" + port + "/");
     listener.Start();
     listener.BeginGetContext(ListenedRequest, null);
 }
Ejemplo n.º 9
0
 public void Start()
 {
     httpListener = new HttpListener();
     httpListener.Prefixes.Add("http://localhost:" + this.ListenPort + "/");
     httpListener.Start();
     httpListener.BeginGetContext(this.OnNewRequest, null);
 }
Ejemplo n.º 10
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();
                    }
                }));
            }
Ejemplo n.º 11
0
        public HTTPServer()
        {
            listener = new HttpListener();
            listener.Prefixes.Add("http://*:" + WebAPI.dis.Configuration.Instance.Port + "/");
            listener.Start();

            WhitelistIPs = new List<string>() { };
            if(WebAPI.dis.Configuration.Instance.WhitelistIPs.Count > 0)
            {
                foreach(var ip in WebAPI.dis.Configuration.Instance.WhitelistIPs)
                {
                    WhitelistIPs.Add(ip.IP);
                }
            }

            AsyncCallback callback = null;
            callback = ar =>
                 {
                     if (!listener.IsListening)
                         return;
                     new Thread(() =>
                     {
                         this.ProcessClient(
                         listener.EndGetContext(ar)
                         );
                     }).Start();
                     listener.BeginGetContext(callback, null);
                 };
            listener.BeginGetContext(callback, null);
        }
Ejemplo n.º 12
0
        public HTTPServer(int port)
        {
            string prefix = string.Format("http://{0}:{1}/", Settings.Default.AddressToListenOn, port);

            httpListener = new HttpListener();
            httpListener.Prefixes.Add(prefix);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes new instance of <see cref="Server"/>.
 /// </summary>
 /// <param name="url">The url to host the server on.</param>
 /// <param name="resolver">The dependency resolver for the server.</param>
 public Server(string url, IDependencyResolver resolver)
     : base(resolver)
 {
     _url = url.Replace("*", @".*?");
     _listener = new HttpListener();
     _listener.Prefixes.Add(url);
 }
Ejemplo n.º 14
0
		public void Start()
		{
			listener = new HttpListener();
			string virtualDirectory = Configuration.VirtualDirectory;
			if (virtualDirectory.EndsWith("/") == false)
				virtualDirectory = virtualDirectory + "/";
			listener.Prefixes.Add("http://+:" + Configuration.Port + virtualDirectory);
			switch (Configuration.AnonymousUserAccessMode)
			{
				case AnonymousUserAccessMode.None:
					listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
					break;
                case AnonymousUserAccessMode.All:
			        break;
				case AnonymousUserAccessMode.Get:
					listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication |
						AuthenticationSchemes.Anonymous;
			        listener.AuthenticationSchemeSelectorDelegate = request =>
			        {
                        return request.HttpMethod == "GET" || request.HttpMethod == "HEAD" ? 
                            AuthenticationSchemes.Anonymous : 
                            AuthenticationSchemes.IntegratedWindowsAuthentication;
			        };
					break;
                default:
			        throw new ArgumentException("Cannot understand access mode: " + Configuration.AnonymousUserAccessMode   );
			}

			listener.Start();
			listener.BeginGetContext(GetContext, null);
		}
Ejemplo n.º 15
0
		public void Run ()
		{
			mainScheduler = TaskScheduler.FromCurrentSynchronizationContext ();

			Task.Run (() => {
				var url = "http://+:" + port + "/";

				var remTries = 2;

				while (remTries > 0) {
					remTries--;

					listener = new HttpListener ();
					listener.Prefixes.Add (url);

					try {
						listener.Start ();
						remTries = 0;
					} catch (HttpListenerException ex) {
						if (remTries == 1 && ex.ErrorCode == 5) { // Access Denied
							GrantServerPermission (url);
						} else {
							throw;
						}
					}
				}

				Loop ();
			});
		}
Ejemplo n.º 16
0
        public void Start()
        {
            if (_isStarted)
            {
                return;
            }

            if (Port == 0)
            {
                throw new Exception("Порт не инициализирован");
            }
            if (String.IsNullOrEmpty(Address))
            {
                throw new Exception("Адрес не инициализирован");
            }

            var prefix = String.Format("http://{0}:{1}/", Address, Port);

            _listener = new System.Net.HttpListener();
            _listener.Prefixes.Add(prefix);
            _listener.Start();

            for (int i = 0; i < MaxConnections; i++)
            {
                AddConnectionForListener();
            }

            _isStarted = true;
        }
 public void Httpserver()
 {
     System.Net.HttpListener lisener = null;
     try
     {
         lisener = new HttpListener();
         lisener.Prefixes.Add("http://localhost:8080/simpleserver/");
         lisener.Start();
         while (true)
         {
             Console.WriteLine("Waiting..");
             HttpListenerContext context = lisener.GetContext();
             string msg = "hello world";
             context.Response.ContentLength64 = Encoding.UTF8.GetByteCount(msg);
             context.Response.StatusCode      = (int)HttpStatusCode.OK;
             using (Stream stream = context.Response.OutputStream)
             {
                 using (StreamWriter writer = new StreamWriter(stream))
                 {
                     writer.Write(msg);
                 }
             }
             Console.WriteLine("Msg sent");
         }
     }
     catch (WebException e)
     {
         Console.WriteLine(e.Status);
     }
 }
Ejemplo n.º 18
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();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Shut down the Web Service
        /// </summary>
        public virtual void Stop()
        {
            if (Listener == null)
            {
                return;
            }

            try
            {
                this.Listener.Close();

                // remove Url Reservation if one was made
                if (registeredReservedUrl != null)
                {
                    RemoveUrlReservationFromAcl(registeredReservedUrl);
                    registeredReservedUrl = null;
                }
            }
            catch (HttpListenerException ex)
            {
                if (ex.ErrorCode != RequestThreadAbortedException)
                {
                    throw;
                }

                Log.Error("Swallowing HttpListenerException({0}) Thread exit or aborted request".Fmt(RequestThreadAbortedException), ex);
            }
            this.IsStarted = false;
            this.Listener  = null;
        }
 /// <summary>
 /// Creates a listener wrapper that can be configured by the user before starting.
 /// </summary>
 internal OwinHttpListener()
 {
     _listener = new System.Net.HttpListener();
     _startNextRequestAsync = new Action(ProcessRequestsAsync);
     _startNextRequestError = new Action <Task>(StartNextRequestError);
     SetRequestProcessingLimits(DefaultMaxAccepts, DefaultMaxRequests);
 }
Ejemplo n.º 21
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();
			}
		}
Ejemplo n.º 22
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);
                    }
                }
            });
        }
Ejemplo n.º 23
0
 public void Stop()
 {
     if (_listener != null) {
         _listener.Stop ();
         _listener = null;
     }
 }
Ejemplo n.º 24
0
        private async Task StartServer()
        {
            HttpServ = new HttpListener();
            btnStartHttpServ.Text = "Stop Server";
            HttpServ.Prefixes.Add("http://localhost:" + txtHttpPort.Value.ToString() + "/");
            HttpServ.Start();
            txtHttpLog.Text += "Start Listining on Port :" + txtHttpPort.Value + "\r\n";
            txtHttpLog.Text += "Server is Running...\r\n\r\n";
            while (true)
            {
                try
                {
                    var ctx = await HttpServ.GetContextAsync();


                    txtHttpLog.Text += "Request: " + ctx.Request.Url.AbsoluteUri + "\r\n";
                    var page = Application.StartupPath + "\\wwwroot" + ctx.Request.Url.LocalPath;
                    if (File.Exists(page))
                    {
                        string file;
                        var ext = new FileInfo(page);
                        if (ext.Extension == ".php")
                        {
                            file = ProcessPhpPage(PhpCompilerPath, page);
                            txtHttpLog.Text += "Processing php page...\r\n";
                        }
                        else
                        {
                            file = File.ReadAllText(page);
                        }

                        await ctx.Response.OutputStream.WriteAsync(ASCIIEncoding.UTF8.GetBytes(file), 0, file.Length);
                        ctx.Response.OutputStream.Close();
                        ctx.Response.Close();
                        txtHttpLog.Text += "Response: 200 OK\r\n\r\n";

                    }
                    else
                    {
                        ctx.Response.StatusCode = 404;
                        var file = "<h2 style=\"color:red;\">404 File Not Found !!!</h2>";
                        await ctx.Response.OutputStream.WriteAsync(ASCIIEncoding.UTF8.GetBytes(file), 0, file.Length);
                        ctx.Response.OutputStream.Close();

                        ctx.Response.Close();
                        txtHttpLog.Text += "Response: 404 Not Found\r\n\r\n";

                    }
                }
                catch (Exception ex)
                {
                    txtHttpLog.Text += "\r\nException: Server Stopped!!!\r\n\r\n";
                   // txtHttpLog.Text += "\r\nException: " + ex.Message + "\r\n\r\n";
                    break;
                }
                txtHttpLog.Select(0, 0);
            }


        }
        public MyApi()
        {
            var httpListener = new System.Net.HttpListener();

            httpListener.Prefixes.Add(MyEndPoint.Uri.ToString());
            httpListener.Start();
        }
Ejemplo n.º 26
0
        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();
        }
Ejemplo n.º 27
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++;
            }
        }
Ejemplo n.º 28
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);
                        }
                    }
                }
                ));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Dispose(bool disposing) executes in two distinct scenarios.
        /// If disposing equals true, the method has been called directly
        /// or indirectly by a user's code. Managed and unmanaged resources
        /// can be disposed.
        /// If disposing equals false, the method has been called by the
        /// runtime from inside the finalizer and you should not reference
        /// other objects. Only unmanaged resources can be disposed.
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!this._disposed)
            {
                // Note disposing has been done.
                _disposed = true;

                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (_listener != null)
                    {
                        _listener.Close();
                    }
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                _listener = null;
                _queue    = null;
            }
        }
Ejemplo n.º 30
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
                }
            }
        }
Ejemplo n.º 31
0
        public static async void ThreadProcAsync()
        {
            string uriPrefix = ConfigurationManager.AppSettings["ListenerPrefix"];

            using (System.Net.HttpListener listener = new System.Net.HttpListener())
            {
                listener.Prefixes.Add(uriPrefix);

                listener.IgnoreWriteExceptions = true;

                // For the sake of the development convenience, this code opens default web browser
                // with this server url when project is started in the debug mode as a console app.
#if DEBUG
                if (!IsServiceMode)
                {
                    System.Diagnostics.Process.Start(uriPrefix.Replace("+", "localhost"), null);
                }
#endif


                listener.Start();

                Console.WriteLine("Start listening on " + uriPrefix);
                Console.WriteLine("Press Control-C to stop listener...");

                while (Listening)
                {
                    HttpListenerContext context = await listener.GetContextAsync();

#pragma warning disable 4014
                    Task.Factory.StartNew(() => ProcessRequestAsync(listener, context));
#pragma warning restore 4014
                }
            }
        }
Ejemplo n.º 32
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();
            }
        }
Ejemplo n.º 33
0
        public AsyncServer(params string[] prefixes)
        {
            _listener = new HttpListener();
            _listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            foreach (string s in prefixes)
                _listener.Prefixes.Add(s);

            Routes = new List<IRoute>()
            {
                new RouteMatchAction
                {
                    MatchString = "time",
                    MatchRule   = RouteMatch.RouteMatchRule.Basic,
                    Priority    = int.MaxValue,
                    ActionAsync = GetTime
                },
                new RouteMatchAction
                {
                    MatchString = "info",
                    MatchRule   = RouteMatch.RouteMatchRule.Basic,
                    Priority    = int.MaxValue,
                    ActionAsync = GetInfo
                }
            };
        }
 public static void AssembyInitialize(TestContext testcontext)
 {
     listener = new HttpListener();
     listener.Prefixes.Add("http://+:" + Port + WebSocketConstants.UriSuffix + "/");
     listener.Start();
     RunWebSocketServer().Fork();
 }
 public HttpCommunicationListener(string uriPrefix, string uriPublished, Func<HttpListenerContext, CancellationToken, Task> processRequest)
 {
     this.publishUri = uriPublished;
     this.processRequest = processRequest;
     this.httpListener = new HttpListener();
     this.httpListener.Prefixes.Add(uriPrefix);
 }
Ejemplo n.º 36
0
        static void Main(string[] args)
        {
            // Create a HTTP listener.
            HttpListener listener = new HttpListener();

            listener.Prefixes.Add(MyEndpoint);
            listener.Start(); // will abort if port not permitted and not running in Administrator mode.

            try
            {
                ListenerLoop(listener);
                Console.Write(DateTime.UtcNow + ": Listening at");
                foreach (string p in listener.Prefixes)
                    Console.Write(" " + p);
                Console.WriteLine("\nPress any key to exit...");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: Message:" + ex.Message);
            }
            finally
            {
                listener.Close();
            }
        }
Ejemplo n.º 37
0
        private static async void DispatchHttpRequestsAsync(System.Net.HttpListener httpListener, CancellationToken cancellationToken)
        {
            // Create a request handler factory that uses basic authentication
            var requestHandlerFactory = new RequestHandlerFactory();

            // Create WebDAV dispatcher
            var homeFolder       = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            var webDavDispatcher = new WebDavDispatcher(new DiskStore(homeFolder), requestHandlerFactory);

            // Determine the WebDAV username/password for authorization
            // (only when basic authentication is enabled)
            var webdavUsername = ConfigurationManager.AppSettings["webdav.username"] ?? "test";
            var webdavPassword = ConfigurationManager.AppSettings["webdav.password"] ?? "test";

            HttpListenerContext httpListenerContext;

            while (!cancellationToken.IsCancellationRequested && (httpListenerContext = await httpListener.GetContextAsync().ConfigureAwait(false)) != null)
            {
                // Determine the proper HTTP context
                IHttpContext httpContext;
                if (httpListenerContext.Request.IsAuthenticated)
                {
                    httpContext = new HttpBasicContext(httpListenerContext, checkIdentity: i => i.Name == webdavUsername && i.Password == webdavPassword);
                }
                else
                {
                    httpContext = new HttpContext(httpListenerContext);
                }

                // Dispatch the request
                await webDavDispatcher.DispatchRequestAsync(httpContext).ConfigureAwait(false);
            }
        }
		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();
		}
Ejemplo n.º 39
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();
			}
		}
Ejemplo n.º 40
0
        public void Start()
        {
            logger = LoggerFactory.GetLogger("SimpleHttpServer.Server");

            logger.Info("Server starting on port {0}", port);

            if (listener != null)
            {
                logger.Fatal("Server already started");
                throw new InvalidOperationException("Already started");
            }

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

            try
            {
                listener.Start();
            }
            catch(Exception ex)
            {
                logger.Fatal("Error starting server", ex);
                throw;
            }

            logger.Info("Server started");

            logger.Debug("Waiting for first request");
            listener.BeginGetContext(ProcessRequest, null);
        }
Ejemplo n.º 41
0
		public void GetContext2 ()
		{
			HttpListener listener = new HttpListener ();
			listener.Start ();
			// "Please call AddPrefix () before calling this method"
			listener.GetContext ();
		}
Ejemplo n.º 42
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);
                        }
                    }
                }
            });
        }
        static int SelectNextAvailablePort()
        {
            var usedPorts = new List<int>();
            var r = new Random();
            int newPort;

            while (true)
            {
                using (var mListener = new HttpListener())
                {
                    newPort = r.Next(49152, 65535);
                    if (usedPorts.Contains(newPort))
                    {
                        continue;
                    }
                    mListener.Prefixes.Add(string.Format("http://localhost:{0}/", newPort));
                    try
                    {
                        mListener.Start();
                    }
                    catch
                    {
                        continue;
                    }
                }
                usedPorts.Add(newPort);
                break;
            }

            return newPort;
        }
Ejemplo n.º 44
0
        public void Start()
        {
            _httpListener = new System.Net.HttpListener();

            _httpListener.Prefixes.Add($"http://+:{_port}/");

            _httpListener.Start();
        }
Ejemplo n.º 45
0
 /// <summary>
 /// 释放
 /// </summary>
 public void Dispose()
 {
     if (listener != null)
     {
         listener.Stop();
         listener = null;
     }
 }
Ejemplo n.º 46
0
        /// <exclude />
        public override void Open()
        {
            mHttpListener = new System.Net.HttpListener();
            mHttpListener.Prefixes.Add(mUrl);
            mHttpListener.Start();

            Task.Run(ListenAsync);
        }
        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();
        }
Ejemplo n.º 48
0
 public void Stop()
 {
     if (Listener != null)
     {
         Listener.Close();
         Listener  = null;
         IsStarted = false;
     }
 }
Ejemplo n.º 49
0
 /// <summary>
 /// Creates a listener wrapper that can be configured by the user before starting.
 /// </summary>
 internal OwinHttpListener()
 {
     _listener = new System.Net.HttpListener();
     _startNextRequestAsync  = new Action(StartNextRequestAsync);
     _startNextRequestError  = new Func <CatchInfo, CatchInfoBase <Task> .CatchResult>(StartNextRequestError);
     _startProcessingRequest = new Action <HttpListenerContext>(StartProcessingRequest);
     _handleAcceptError      = new Func <CatchInfo, CatchInfoBase <Task> .CatchResult>(HandleAcceptError);
     SetRequestProcessingLimits(DefaultMaxAccepts, DefaultMaxRequests);
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Starts the listener and request processing threads.
        /// </summary>
        internal void Start(System.Net.HttpListener listener, AppFunc appFunc, IList <IDictionary <string, object> > addresses,
                            IDictionary <string, object> capabilities, LoggerFactoryFunc loggerFactory)
        {
            Contract.Assert(_appFunc == null); // Start should only be called once
            Contract.Assert(listener != null);
            Contract.Assert(appFunc != null);
            Contract.Assert(addresses != null);

            _listener      = listener;
            _appFunc       = appFunc;
            _loggerFactory = loggerFactory;
            if (_loggerFactory != null)
            {
                _logger = _loggerFactory(typeof(OwinHttpListener).FullName);
            }

            _basePaths = new List <string>();

            foreach (var address in addresses)
            {
                // build url from parts
                string scheme = address.Get <string>("scheme") ?? Uri.UriSchemeHttp;
                string host   = address.Get <string>("host") ?? "localhost";
                string port   = address.Get <string>("port") ?? "5000";
                string path   = address.Get <string>("path") ?? string.Empty;

                // if port is present, add delimiter to value before concatenation
                if (!string.IsNullOrWhiteSpace(port))
                {
                    port = ":" + port;
                }

                // Assume http(s)://+:9090/BasePath/, including the first path slash.  May be empty. Must end with a slash.
                if (!path.EndsWith("/", StringComparison.Ordinal))
                {
                    // Http.Sys requires that the URL end in a slash
                    path += "/";
                }
                _basePaths.Add(path);

                // add a server for each url
                string url = scheme + "://" + host + port + path;
                _listener.Prefixes.Add(url);
            }

            _capabilities      = capabilities;
            _disconnectHandler = new DisconnectHandler(_listener);

            if (!_listener.IsListening)
            {
                _listener.Start();
                _disconnectHandler.Initialize();
            }

            OffloadStartNextRequest();
        }
Ejemplo n.º 51
0
        private void connected(IAsyncResult result)
        {
            System.Net.HttpListener listener = (System.Net.HttpListener)result.AsyncState;
            HttpListenerContext     context  = listener.EndGetContext(result);

            requestedPath = context.Request.Url.AbsolutePath;
            context.Response.StatusCode = this.response;

            context.Response.OutputStream.Close();
        }
Ejemplo n.º 52
0
 public void Configure(string[] prefixes, string vdir, string pdir)
 {
     _virtualDir  = vdir;
     _physicalDir = pdir;
     _listener    = new System.Net.HttpListener();
     foreach (string prefix in prefixes)
     {
         _listener.Prefixes.Add(prefix);
     }
 }
Ejemplo n.º 53
0
 public void Stop()
 {
     if (!IsRunning)
     {
         return;
     }
     listener.Close();
     listener.Abort();
     listener = null;
 }
Ejemplo n.º 54
0
        public void Start(string uriPrefix, Action <HttpListenerContext> sessionReceived)
        {
            _httpServer = new System.Net.HttpListener();
            _httpServer.Prefixes.Add(uriPrefix);
            _httpServer.Start();

            _running = true;

            _httpServer.BeginGetContext(HandleRequest, new SessionState(this, sessionReceived));
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Start the http listener.
        /// </summary>
        public async void Start()
        {
            // If not running.
            if (!_running)
            {
                try
                {
                    // Create a new http listener
                    if (_listener == null)
                    {
                        _listener = new System.Net.HttpListener();

                        // Add URI prefixes to listen for.
                        foreach (string uri in _uriList)
                        {
                            _listener.Prefixes.Add(uri);
                        }
                    }

                    // Set the Authentication Schemes.
                    _listener.AuthenticationSchemes = _authenticationSchemes;
                    if (_authenticationSchemeSelectorDelegate != null)
                    {
                        _listener.AuthenticationSchemeSelectorDelegate = _authenticationSchemeSelectorDelegate;
                    }

                    // Start the listener
                    _listener.Start();
                    _running = true;

                    // Keep the service in the running start
                    // listen for in-comming requests.
                    while (_running)
                    {
                        // Wait for the next request.
                        HttpListenerContext listenerContext = await _listener.GetContextAsync();

                        // Send the http context to the handler.
                        if (listenerContext != null)
                        {
                            AsynchronousListener(listenerContext);
                        }
                    }
                }
                catch (Exception)
                {
                    if (_listener != null)
                    {
                        _listener.Close();
                    }

                    throw;
                }
            }
        }
Ejemplo n.º 56
0
 public virtual void Start()
 {
     try
     {
         _listener = new System.Net.HttpListener();
         _listener.Prefixes.Add(string.Format("http://+:{0}/{1}", Port, Prefix));
         _listener.Start();
         _listener.BeginGetContext(this.Listener_Request, _listener);
     }
     catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
 }
Ejemplo n.º 57
0
        protected void Start(IEnumerable <string> urlBases, WaitCallback listenCallback)
        {
            // *** Already running - just leave it in place
            if (this.IsStarted)
            {
                return;
            }

            if (this.Listener == null)
            {
                Listener = CreateHttpListener();
            }

            foreach (var urlBase in urlBases)
            {
                if (HostContext.Config.HandlerFactoryPath == null)
                {
                    HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(urlBase);
                }

                Listener.Prefixes.Add(urlBase);
            }

            try
            {
                Listener.Start();
                IsStarted = true;
            }
            catch (HttpListenerException ex)
            {
                if (Config.AllowAclUrlReservation && ex.ErrorCode == 5 && registeredReservedUrl == null)
                {
                    foreach (var urlBase in urlBases)
                    {
                        registeredReservedUrl = AddUrlReservationToAcl(urlBase);
                        if (registeredReservedUrl == null)
                        {
                            break;
                        }
                    }

                    if (registeredReservedUrl != null)
                    {
                        Listener = null;
                        Start(urlBases, listenCallback);
                        return;
                    }
                }

                throw ex;
            }

            ThreadPool.QueueUserWorkItem(listenCallback);
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Starts listening for incoming connections
        /// </summary>
        public override void Start()
        {
            if (Running)
            {
                return;
            }

            listener = new System.Net.HttpListener();
            listener.Prefixes.Add(prefix);
            listener.Start();
            listener.BeginGetContext(EndGetRequest, listener);
        }
Ejemplo n.º 59
-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);
                }
            }
        }
Ejemplo n.º 60
-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();
            }
        }