当前位置: 首页>>代码示例>>C#>>正文


C# HttpListener.Stop方法代码示例

本文整理汇总了C#中System.Net.HttpListener.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListener.Stop方法的具体用法?C# HttpListener.Stop怎么用?C# HttpListener.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.HttpListener的用法示例。


在下文中一共展示了HttpListener.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        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();
        }
开发者ID:Jupotter,项目名称:virologie,代码行数:27,代码来源:Program.cs

示例2: LocalPathWithoutQuery_SpecialCharactersDecodedCorrectly

        public void LocalPathWithoutQuery_SpecialCharactersDecodedCorrectly(string urlEnd, string expectedResult)
        {
            var listener = new HttpListener();
            // Nothing special about 33579. It is a simply a random number we hope is unused.
            // Note: if you get errors indicating the port is in use,
            // it is likely the listener.Stop() line below wasn't called somehow.
            var urlPrefix = "http://localhost:33579/";
            listener.Prefixes.Add(urlPrefix);

            var reqThread = new Thread(() =>
            {
                Thread.Sleep(100);
                WebRequest req = WebRequest.Create(urlPrefix + urlEnd);
                req.GetResponse();
            });
            reqThread.Start();

            try
            {
                listener.Start();
                var context = listener.GetContext(); // This waits for a request.
                var requestInfo = new RequestInfo(context);
                Assert.AreEqual(expectedResult, requestInfo.LocalPathWithoutQuery);
            }
            finally
            {
                listener.Stop();
                reqThread.Join();
            }
        }
开发者ID:BloomBooks,项目名称:BloomDesktop,代码行数:30,代码来源:RequestInfoTests.cs

示例3: Start

        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();
        }
开发者ID:JeanGe1988,项目名称:SimpleWebServer,代码行数:29,代码来源:Server.cs

示例4: AuthenticateAsync

        public async Task<ICredential> AuthenticateAsync(Uri requestUri, Uri callbackUri = null)
        {
			var requestUriStrb = new StringBuilder();
			requestUriStrb.Append(requestUri.AbsoluteUri);
			
			if (callbackUri != null)
			{
				requestUriStrb.AppendFormat("&oauth_callback={0}", callbackUri.AbsoluteUri);
			}
			
			var listener = new HttpListener();
			listener.Prefixes.Add(callbackUri.AbsoluteUri);
			listener.Start();
			
			System.Diagnostics.Process.Start(requestUriStrb.ToString());
			
			var ctx = await listener.GetContextAsync();
			
			var token = new Credential(ctx.Request.QueryString.Get("oauth_token"), ctx.Request.QueryString.Get("oauth_verifier"));
			
			// empty response
			// ctx.Response.ContentLength64 = 0;
			// await ctx.Response.OutputStream.WriteAsync(new byte[0], 0, 0);
			ctx.Response.OutputStream.Close();
			
			listener.Stop();
			
			return token;
        }
开发者ID:luzianz,项目名称:TwitterClient,代码行数:29,代码来源:ConsoleWebAuthenticationBroker.cs

示例5: Stop

 public void Stop(HttpListener listener, Task handleRequests, Task updateWorld)
 {
     _exiting = true;
     listener.Stop();
     updateWorld.Wait(TimeSpan.FromSeconds(2));
     handleRequests.Wait(TimeSpan.FromSeconds(2));
 }
开发者ID:vvnurmi,项目名称:MOOLGOSS,代码行数:7,代码来源:Server.cs

示例6: Main

        static void Main(string[] args)
        {
            THNETII.AssemblySplash.WriteAssemblySplash();

            Console.WriteLine();

            if (args == null || args.Length < 1 || !int.TryParse(args[0], out portNumber))
                portNumber = 8899;

            string host = "+";
            if (args != null && args.Length > 1)
                host = args[1];

            nodeGuid = Guid.NewGuid();

            Console.CancelKeyPress += OnTerminateSignal;

            var http_listener = new HttpListener();
            http_listener.Prefixes.Add(string.Format("http://{0}:{1}/", host, portNumber));

            http_listener.Start();
            HandleHttpContext(http_listener);

            terminateSignal.WaitOne();

            ClearConnectionsContext();

            http_listener.Stop();
        }
开发者ID:TTeige,项目名称:inf3200-teige-tim,代码行数:29,代码来源:Program.cs

示例7: Main

        private static void Main(string[] args)
        {
            HTTPGet req = new HTTPGet();
            req.Request("http://checkip.dyndns.org");
            string[] a = req.ResponseBody.Split(':');
            string a2 = a[1].Substring(1);
            string[] a3 = a2.Split('<');
            string a4 = a3[0];
                            listener = new HttpListener();
                            listener.Prefixes.Add("http://*:" + port + "/");
                            listener.Start();

                            listen = new Thread(ListenerCallback);
                            listen.Start();
                            for (int i = 0; i < workers.Length; i++)
                            {
                                workers[i] = new Thread(Worker);
                                workers[i].Start();
                            }
                            Console.CancelKeyPress += (sender, e) =>
                            {
                                Console.WriteLine("Terminating...");
                                listener.Stop();
                                while (contextQueue.Count > 0)
                                    Thread.Sleep(100);
                                Environment.Exit(0);
                            };
                            Console.WriteLine("Listening at port " + port + "...");
                            Console.WriteLine("Server IP: " + a4);
                            Thread.CurrentThread.Join();
        }
开发者ID:C453,项目名称:OryxKingdom,代码行数:31,代码来源:Program.cs

示例8: Main

        static void Main(string[] args)
        {
            try
            {
                dbaddr = db.confreader.getservers(true);
                listener = new HttpListener();
                listener.Prefixes.Add("http://*:" + port + "/");
                listener.Start();
                listen = new Thread(ListenerCallback);
                listen.Start();
                for (var i = 0; i < workers.Length; i++)
                {
                    workers[i] = new Thread(Worker);
                    workers[i].Start();
                }
                Console.CancelKeyPress += (sender, e) =>
                {
                    Console.WriteLine("Terminating...");
                    listener.Stop();
                    while (contextQueue.Count > 0)
                        Thread.Sleep(100);
                    Environment.Exit(0);
                };
                Console.WriteLine("Listening at port " + port + "...");

                Thread.CurrentThread.Join();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
                Console.ReadLine();
            }
        }
开发者ID:lcnvdl,项目名称:rotmg-server,代码行数:33,代码来源:Program.cs

示例9: InterceptUserTokens

        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;
        }
开发者ID:Brightspace,项目名称:sample-valence-client-side,代码行数:26,代码来源:Program.cs

示例10: Main

        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();
        }
开发者ID:Zeroeh,项目名称:PrivateServerOld,代码行数:28,代码来源:Program.cs

示例11: Main

        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();
        }
开发者ID:Carlovan,项目名称:PokerLAN,代码行数:33,代码来源:Program.cs

示例12: HttpListenForOneRequest

        public Task<string> HttpListenForOneRequest()
        {
            return new Task<string>(() =>
            {
                var url = ConfigurationManager.AppSettings["httpListenerUrl"];

                var listener = new HttpListener();
                listener.Prefixes.Add(url);
                listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
                listener.TimeoutManager.IdleConnection = TimeSpan.FromMilliseconds(500);
                listener.Start();
                
                HttpListenerContext context = listener.GetContextAsync().Result;

                string requestContent;
                using (var r = new StreamReader(context.Request.InputStream))
                {
                    requestContent = r.ReadToEnd();
                }

                context.Response.StatusCode = 200;
                context.Response.Close();
                listener.Stop();

                return requestContent;
            });
        }
开发者ID:CaseyBurns,项目名称:log4net.ext.JsonHttpAppender,代码行数:27,代码来源:JsonHttpAppenderTests.cs

示例13: BasicRoundTrip

		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();
		}
开发者ID:BrannonKing,项目名称:Kts.Remoting,代码行数:31,代码来源:SystemWebSocketsFullCircle.cs

示例14: Run

        /// <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);
            }
        }
开发者ID:nixxa,项目名称:HttpServer,代码行数:28,代码来源:Service.cs

示例15: Main

		static HttpListener listener; // http server providing clipboard history selection

		public static void Main (string[] args)
		{
			// make UI methods for clipboard access available
			Application.Init ();

			// setup http interface
			listener = new HttpListener();
			listener.Prefixes.Add("http://*:5544/");
			listener.Start();
			listener.BeginGetContext(ProcessRequest, null);

			// initialize access to clipboard
			clippy = Gtk.Clipboard.Get(Gdk.Atom.Intern("PRIMARY", false));

			// schedule polling of clipboard content
			timer = new System.Timers.Timer(300);
			timer.Elapsed += new System.Timers.ElapsedEventHandler(ReadClipboardUI);
			timer.Start();

			// just to prevent termination of the app
			Application.Run();

			// shutdown http interface
			listener.Stop();
		}
开发者ID:eugenkrizo,项目名称:tablet-clipboard,代码行数:27,代码来源:Main.cs


注:本文中的System.Net.HttpListener.Stop方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。