通过HttpListener实现简单的Http服务
来源:互联网 发布:婚礼录像后期制作软件 编辑:程序博客网 时间:2024/06/01 08:39
注意:该类仅在运行 Windows XP SP2 或 Windows Server 2003 操作系统的计算机上可用。
使用Http服务一般步骤如下:
- 创建一个HTTP侦听器对象并初始化
- 添加需要监听的URI 前缀
- 开始侦听来自客户端的请求
- 处理客户端的Http请求
- 关闭HTTP侦听器
其中3,4两步可以循环处理,以提供多客户多次请求的服务。
创建一个HTTP侦听器对象
创建HTTP侦听器对象只需要新建一个HttpListener对象即可。
HttpListener listener =new HttpListener();
初始化需要经过如下两步
- 添加需要监听的URL范围至listener.Prefixes中,可以通过如下函数实现:
listener.Prefixes.Add(prefix) //prefix必须以'/'结尾 - 调用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中的Request和Response的使用方式类似,这里就不多说了,具体的使用可以参看下面的例子。
关闭HTTP侦听器
通过调用listener.Stop()函数即可关闭侦听器,并释放相关资源
代码示例:
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...");
//阻塞主函数至接收到一个客户端请求为止
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
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();
listener.Stop(); //关闭HttpListener
}
}
}
该程序功能比较简单,首先创建了一个HTTP侦听器,使其实现对"http://localhost/time/"域的服务,接收到一个远程请求时,将当前时间转换为字符串输出给客户端,然后关闭侦听器。
- 通过HttpListener实现简单的Http服务
- 通过HttpListener实现简单的Http服务
- 通过HttpListener实现简单的Http服务
- 【通过HttpListener实现简单的Http服务】
- 通过HttpListener实现简单的Http服务
- 通过HttpListener实现简单的Http服务(监听)
- 通过HttpListener实现简单的Http服…
- 一个简单的HttpListener服务结构
- 一个简单的HttpListener服务结构
- 使用HttpListener 实现简单的web服务器
- 使用HttpListener实现简单Web服务器
- 03-基于HttpListener的Web服务
- 简单基于HttpListener的Web服务器实例
- 利用Httplistener实现的HttpServer类
- 在iPhone上实现简单Http服务
- 在iPhone上实现简单Http服务
- 在iPhone上实现简单Http服务
- 在iPhone上实现简单Http服务
- 今天学习的一点python
- Ubuntu下安装virtualbox虚拟windows xp后设置bridge网络连接访问ipv6
- iReport4 database JDBC connection 找不到驱动
- 用dump备份数据库结构和数据。
- Spring基于 Annotation 的简单介绍
- 通过HttpListener实现简单的Http服务
- 报表,饼图(曲线图)
- 悄悄的十月
- C++学习-构造函数(续)
- qt翻译工程--经验记载
- 面试技巧
- QT国际化的应用
- Spring对注解(Annotation)处理源码分析1——扫描和读取Bean定义
- java:ArrayList,Vector,LinkedList的实现