• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Net.HttpListener类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: Start

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


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


示例18: StartServer

        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);
            }


        }
开发者ID:EslaMx7,项目名称:SimpleHttpServer,代码行数:60,代码来源:frmMain.cs


示例19: Server

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


示例20: CreateAndStartListener

		public static HttpListener CreateAndStartListener (string prefix)
		{
			HttpListener listener = new HttpListener ();
			listener.Prefixes.Add (prefix);
			listener.Start ();
			return listener;
		}
开发者ID:frje,项目名称:SharpLang,代码行数:7,代码来源:HttpListener2Test.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Net.HttpListenerContext类代码示例发布时间:2022-05-26
下一篇:
C# Net.FtpWebResponse类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap