C# 创建HttpServer

来源:互联网 发布:河南豫广网络有线电视 编辑:程序博客网 时间:2024/05/16 18:35
时间:2016.10.28

在C#中使用HttpListener实现HttpServer的简单示例


[ Program.cs ]

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.Threadingnamespace httpServer{    class Program    {        static void Main(string[] args)        {            HttpListener httpListener;            httpListener = new HttpListener();            httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;            httpListener.Prefixes.Add("http://127.0.0.1:8086/");            httpListener.Start();            new Thread( new ThreadStart( delegate {                try{                    loop(httpListener);                }                catch(Exception)                {                    httpListener.Stop();                }            })).Start();        }        private static void loop(HttpListener httpListener)        {            while (true)            {                HttpListenerContext context = httpListener.GetContext();                HttpListenerRequest hRequest = context.Request;                HttpListenerResponse hResponse = context.Response;                if (hRequest.HttpMethod == "POST")                {                     Console.WriteLine("POST:" + hRequest.Url);            byte[] res = Encoding.UTF8.GetBytes("OK");            hResponse.OutputStream.Write(res, 0, res.Length);                }                else if (hRequest.HttpMethod == "GET")                {                    Console.WriteLine( "GET:"+hRequest.Url);                    byte[] res = Encoding.UTF8.GetBytes("OK");                    hResponse.OutputStream.Write(res, 0, res.Length);                }            }            httpListener.Close();        }    }}

运行结果:
1). 在浏览器中输入 127.0.0.1:8086
测试结果
2). 在浏览器中输入(本机IP) 192.168.40.178:8086 没有显示内容

总结:
… 1. HttpListener的GetContext是阻塞型的

问题:
Q1: httpListener.Prefixes.Add的时候如果端口号设置成80,则下面运行到httpListener.Start的时候会报异常?

Q2: 为什么本机IP的时候不现实内容?

0 0