《http篇》通过HttpListener实现http服务

发布时间 2023-08-02 11:54:49作者: Fusio

简单http服务

如果想实现更高级http服务,可以看下述目录

参考链接:https://blog.csdn.net/qq_36702996/article/details/78892380

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

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

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

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

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

创建一个HTTP侦听器对象

详细介绍:

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

HttpListener listener = new HttpListener();

2、初始化需要经过一下两步

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

3、接收HTTP请求

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

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

HttpListenerContext context = listener.GetContext();

该方法将阻塞调用函数至接收一个客户端请求为止,如果要提高响应速度,可使用异步方法

listener.BeginGetContext()

来实现HttpListenerContext对象的获取。

4、处理HTTP请求

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

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

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

5、关闭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/" 域的服务,接收到一个远程请求时,将当前时间转换为字符串输出给客户端,然后关闭侦听器。

报错System.Net.HttpListenerException拒绝访问

参考链接:https://blog.csdn.net/m0_37611330/article/details/125759529

只需要将生成的exe设置成管理员身份运行,往后就不会再报错了