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


C# Net.HttpListener类代码示例

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


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

示例1: GetContext2

		public void GetContext2 ()
		{
			HttpListener listener = new HttpListener ();
			listener.Start ();
			// "Please call AddPrefix () before calling this method"
			listener.GetContext ();
		}
开发者ID:acsey,项目名称:mono,代码行数:7,代码来源:HttpListenerTest.cs

示例2: HTTPServer

        public HTTPServer(int port)
        {
            string prefix = string.Format("http://{0}:{1}/", Settings.Default.AddressToListenOn, port);

            httpListener = new HttpListener();
            httpListener.Prefixes.Add(prefix);
        }
开发者ID:acid2000,项目名称:OfficeCheevos,代码行数:7,代码来源:HTTPServer.cs

示例3: Start

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

示例4: Listen

        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);
                }
            }
        }
开发者ID:neutra,项目名称:uLuaGameFramework,代码行数:30,代码来源:HttpService.cs

示例5: 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

示例6: Start

 public void Start()
 {
     httpListener = new HttpListener();
     httpListener.Prefixes.Add("http://localhost:" + this.ListenPort + "/");
     httpListener.Start();
     httpListener.BeginGetContext(this.OnNewRequest, null);
 }
开发者ID:semirs,项目名称:CellAO,代码行数:7,代码来源:MicroHttpServer.cs

示例7: Main

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

示例8: Server

 /// <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);
 }
开发者ID:nightbob3,项目名称:SignalR,代码行数:12,代码来源:Server.cs

示例9: AssembyInitialize

 public static void AssembyInitialize(TestContext testcontext)
 {
     listener = new HttpListener();
     listener.Prefixes.Add("http://+:" + Port + WebSocketConstants.UriSuffix + "/");
     listener.Start();
     RunWebSocketServer().Fork();
 }
开发者ID:pierreca,项目名称:azure-iot-sdks,代码行数:7,代码来源:ClientWebSocketTransportTests.cs

示例10: Main

        // 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);
            }
        }
开发者ID:shrimpy,项目名称:GitServerSample,代码行数:32,代码来源:Program.cs

示例11: Run

        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();
            }
        }
开发者ID:nazik,项目名称:inst4wa,代码行数:35,代码来源:HelloWorldWorkerRole.cs

示例12: Run

		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 ();
			});
		}
开发者ID:praeclarum,项目名称:Continuous,代码行数:30,代码来源:HttpServer.cs

示例13: AddTask

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

示例14: SelectNextAvailablePort

        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;
        }
开发者ID:johnsimons,项目名称:NServiceBus.Diagnostics,代码行数:31,代码来源:NancyStarter.cs

示例15: OpenFakeHttpServer

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


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