public class HttpWebService
{
#region /*private member*/
/// <summary>
/// 私有Http监听器
/// </summary>
private HttpListener m_Listerner;
/// <summary>
/// 私有线程
/// </summary>
private Thread m_Thread;
/// <summary>
/// 监听IP
/// </summary>
private string m_IP;
/// <summary>
/// 监听端口
/// </summary>
private int m_Port = 8620;
#endregion
#region /*constructor method*/
/// <summary>
/// 构造函数
/// </summary>
public HttpWebService()
{
Init();
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="port">端口号</param>
public HttpWebService(int port)
{
this.m_Port = port;
Init();
}
#endregion
#region /*public method*/
/// <summary>
/// 启动 HTTP Server
/// </summary>
public void Start()
{
Init();
this.m_Thread.Start();
}
/// <summary>
/// 停止 HTTP Server
/// </summary>
public void Stop()
{
if (m_Listerner != null)
{
m_Listerner.Stop();
}
this.m_Thread = null;
}
#endregion
#region /*private method*/
/// <summary>
/// 初始方法
/// </summary>
private void Init()
{
//取IP
this.m_IP = IPHelper.GetLocalIP();
m_Listerner = new HttpListener();
//指定匿名身份验证
m_Listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
//设置URI前缀
m_Listerner.Prefixes.Add("http://" + m_IP + ":" + m_Port + "/api/");
m_Listerner.Prefixes.Add("http://127.0.0.1:" + m_Port + "/api/");
m_Listerner.Prefixes.Add("http://localhost:" + m_Port + "/api/");
this.m_Thread = new Thread(new ThreadStart(myThreadMethod));
this.m_Thread.IsBackground = true;
}
/// <summary>
/// 线程方法
/// </summary>
private void myThreadMethod()
{
m_Listerner.Start();
m_Listerner.BeginGetContext(new AsyncCallback(GetContextCallBack), m_Listerner);//开始异步检索请求
Console.WriteLine("Http Server Start Successed.......");
}
/// <summary>
/// 异步回调方法
/// </summary>
/// <param name="iar">异步操作状态</param>
private void GetContextCallBack(IAsyncResult iar)
{
HttpListenerContext ctx = null;
try
{
m_Listerner = iar.AsyncState as HttpListener;
ctx = m_Listerner.EndGetContext(iar);
//请求处理
RequestProcesing.Working(ctx);
//开始异步检索请求
m_Listerner.BeginGetContext(new AsyncCallback(GetContextCallBack), m_Listerner);
}
catch (HttpListenerException e)
{
Console.WriteLine("HttpListenerException: {0}", e);
}
finally
{
ctx = null;
}
}
#endregion
}