在前文中我简单的介绍了一下HttpListener的用法,并给出了一个简单的代码示例,那个例子主要是为了演示功能,力求简单,而实际使用中并不方便:服务器每启动一次只能处理一个请求。
我针对这个问题简单的将该结构改进了一下,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost/"); //要监听的url范围
listener.Start(); //开始监听端口,接收客户端请求
Console.WriteLine("Listening");
try
{
while (true)
{
//获取一个客户端请求为止
HttpListenerContext context = listener.GetContext();
//将其处理过程放入线程池
System.Threading.ThreadPool.QueueUserWorkItem(ProcessHttpClient, context);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
listener.Stop(); //关闭HttpListener
}
}
//客户请求处理
static void ProcessHttpClient(object obj)
{
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
//do something as you want
string responseString = string.Format("<HTML><BODY> {0}</BODY></HTML>", DateTime.Now);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
//关闭输出流,释放相应资源
output.Close();
}
}
}
在新的代码中,服务器循环阻塞接收每个客户端的请求,然后将处理过程放如线程池,在新的线程中处理,服务器可以接着接收下一个请求并处理了。
我的目的是为了学习Http服务而推出的一个测试架构,并不需要很完善的框架和很高的效率,采用的线程池形式处理简单,直观且有效。并且将客户处理单独放在ProcessHttpClient函数中执行,如果要学习其它功能,只需要修改该函数即可。