一个简单的HttpListener服务结构

前文中我简单的介绍了一下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函数中执行,如果要学习其它功能,只需要修改该函数即可。



下面是一个使用C#创建简单HttpListener服务器的示例代码: ```csharp using System; using System.Net; using System.Text; public class SimpleHttpServer { public static void Main(string[] args) { // 设置监听的地址和端口号 string url = "http://localhost:8080/"; // 创建HttpListener对象 HttpListener listener = new HttpListener(); // 添加要监听的地址 listener.Prefixes.Add(url); // 开始监听 listener.Start(); Console.WriteLine("Server is running..."); while (true) { // 等待客户端请求 HttpListenerContext context = listener.GetContext(); // 获取请求对象 HttpListenerRequest request = context.Request; // 获取请求的HTTP方法(GET, POST等) string httpMethod = request.HttpMethod; // 获取请求的URL string urlRequest = request.Url.ToString(); // 获取请求的内容 string requestBody = new System.IO.StreamReader(request.InputStream, request.ContentEncoding).ReadToEnd(); // 构建响应内容 string responseBody = "<html><body><h1>Hello, World!</h1></body></html>"; // 将响应内容转换为字节数组 byte[] buffer = Encoding.UTF8.GetBytes(responseBody); // 设置响应状态码 context.Response.StatusCode = 200; // 设置响应内容长度 context.Response.ContentLength64 = buffer.Length; // 发送响应内容 context.Response.OutputStream.Write(buffer, 0, buffer.Length); // 关闭响应 context.Response.OutputStream.Close(); } } } ``` 这个例子创建一个HttpListener对象,并设置要监听的地址和端口号。然后使用while循环等待客户端请求。当有客户端请求到达时,它获取请求对象,并从请求对象中获取HTTP方法,URL和内容。然后构建响应内容,并将其发送回客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值