通过HttpListener实现简单的Http服…

来源:互联网 发布:linux查看mysql密码 编辑:程序博客网 时间:2024/06/14 03:34

通过HttpListener实现简单的Http服务

HttpListener提供一个简单的、可通过编程方式控制的HTTP 协议侦听器。通过它可以很容易的提供一些Http服务,而无需启动IIS这类大型服务程序。

注意:该类仅在运行 Windows XP SP2 或 Windows Server 2003 操作系统的计算机上可用。

使用Http服务一般步骤如下:

  1. 创建一个HTTP侦听器对象并初始化
  2. 添加需要监听的URI 前缀
  3. 开始侦听来自客户端的请求
  4. 处理客户端的Http请求
  5. 关闭HTTP侦听器

其中3,4两步可以循环处理,以提供多客户多次请求的服务。

创建一个HTTP侦听器对象

创建HTTP侦听器对象只需要新建一个HttpListener对象即可。

HttpListener listener = new HttpListener();

初始化需要经过如下两步

  1. 添加需要监听的URL范围至listener.Prefixes中,可以通过如下函数实现:
    listener.Prefixes.Add(prefix)    //prefix必须以'/'结尾
  2. 调用listener.Start()实现端口的绑定,并开始监听客户端的需求。

接受HTTP请求

在.net2.0中,通过HttpListenerContext对象提供对HttpListener类使用的请求和响应对象的访问。

获取HttpListenerContext的最简单方式如下:

HttpListenerContext context =listener.GetContext();

该方法将阻塞调用函数至接收到一个客户端请求为止,如果要提高响应速度,可使用异步方法listener.BeginGetContext()来实现HttpListenerContext对象的获取。

处理HTTP请求

获取HttpListenerContext后,可通过Request属性获取表示客户端请求的对象,通过Response属性取表示HttpListener 将要发送到客户端的响应的对象。

HttpListenerRequest request =context.Request;
HttpListenerResponse response =context.Response;

这里的HttpListenerRequest对象和HttpListenerResponse对象和Asp中的RequestResponse的使用方式类似,这里就不多说了,具体的使用可以参看下面的例子。

关闭HTTP侦听器

通过调用listener.Stop()函数即可关闭侦听器,并释放相关资源

代码示例:

using System;
usingSystem.Collections.Generic;
using System.Text;

using System.Net;

namespaceConsoleApplication1
{
    classProgram
    {
        staticvoid Main(string[] args)
        {
            HttpListenerlistener = newHttpListener();
            listener.Prefixes.Add("http://localhost/");//
添加需要监听的url范围
            listener.Start();//开始监听端口,接收客户端请求
            Console.WriteLine("Listening...");

            //
阻塞主函数至接收到一个客户端请求为止
            HttpListenerContextcontext = listener.GetContext();
            HttpListenerRequestrequest = context.Request;
            HttpListenerResponseresponse = context.Response;

            stringresponseString = string.Format("

{0}",DateTime.Now);
            byte[]buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            //对客户端输出相应信息.
            response.ContentLength64= buffer.Length;
            System.IO.Streamoutput = response.OutputStream;
            output.Write(buffer,0, buffer.Length);
            //
关闭输出流,释放相应资源
            output.Close();

            listener.Stop();//
关闭HttpListener
        }
    }
}

该程序功能比较简单,首先创建了一个HTTP侦听器,使其实现对"http://localhost/time/"域的服务,接收到一个远程请求时,将当前时间转换为字符串输出给客户端,然后关闭侦听器。

0 0