C# 通过HttpListener创建HTTP服务

C# 通过HttpListener创建HTTP服务

  • 在C#中可以利用HttpListener来自定义创建HTTP服务,通过HTTP协议进行服务端与多个客户端之间的信息传递
  • 并且可以做成windows系统服务,而不用寄宿在IIS上。
  • 以下为一个demo,分为两部分,一部分为服务端,另一部分为客户端。

服务端:

class Program {
     static HttpListener httpobj;
     static void Main(string[] args){
         //提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。
         httpobj = new HttpListener();
         //定义url及端口号,通常设置为配置文件
         httpobj.Prefixes.Add("http://+:8080/");
         //启动监听器
         httpobj.Start();
         //异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托
         //该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象
         httpobj.BeginGetContext(Result, null);
         Console.WriteLine($"服务端初始化完毕,正在等待客户端请求,时间:{DateTime.Now.ToString()}\r\n");
         Console.ReadKey();
    }

    private static void Result(IAsyncResult ar){
         //当接收到请求后程序流会走到这里

         //继续异步监听
         httpobj.BeginGetContext(Result, null);
         var guid = Guid.NewGuid().ToString();
         Console.ForegroundColor = ConsoleColor.White;
         Console.WriteLine($"接到新的请求:{guid},时间:{DateTime.Now.ToString()}");
         //获得context对象
         var context = httpobj.EndGetContext(ar);
         var request = context.Request;
         var response = context.Response;
         如果是js的ajax请求,还可以设置跨域的ip地址与参数
         //context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件
         //context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件
         //context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件
         context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8
         context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息
         context.Response.ContentEncoding = Encoding.UTF8;
         string returnObj = null;//定义返回客户端的信息
         if (request.HttpMethod == "POST" && request.InputStream != null) {
            //处理客户端发送的请求并返回处理信息
            returnObj = HandleRequest(request, response);
         } else {
            returnObj = $"不是post请求或者传过来的数据为空";
         }
         var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码
         try {
             using (var stream = response.OutputStream) {
                 //把处理信息返回到客户端
                 stream.Write(returnByteArr, 0, returnByteArr.Length);
                }
            } catch (Exception ex) {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"网络蹦了:{ex.ToString()}");
            }
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"请求处理完成:{guid},时间:{ DateTime.Now.ToString()}\r\n");
        }

        private static string HandleRequest(HttpListenerRequest request, HttpListenerResponse response) {
            string data = null;
            try {
                var byteList = new List<byte>();
                var byteArr = new byte[2048];
                int readLen = 0;
                int len = 0;
                //接收客户端传过来的数据并转成字符串类型
                do {
                    readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);
                    len += readLen;
                    byteList.AddRange(byteArr);
                } while (readLen != 0);
                data = Encoding.UTF8.GetString(byteList.ToArray(),0, len);
                //获取得到数据data可以进行其他操作
            } catch (Exception ex) {
                response.StatusDescription = "404";
                response.StatusCode = 404;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");
                return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考
            }
            response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。
            response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"接收数据完成:{data.Trim()},时间:{DateTime.Now.ToString()}");
            return $"接收数据完成";
        }
    }  
客户端:
  class Program{
        static void Main(string[] args){
            string operation;
            do {
                Console.WriteLine("按任意键发送数据到服务端");
                Console.ReadLine();
                var wc = new WebClient();
                var url = "http://127.0.0.1:8080";
                Console.WriteLine($"请求服务地址:{url},时间:{DateTime.Now.ToString()}");
                //模拟一个json数据发送到服务端
                var data = new Data(1, "张三");
                var jsonModel = JsonConvert.SerializeObject(data);
                //发送到服务端并获得返回值
                var returnInfo = wc.UploadData(url, Encoding.UTF8.GetBytes(jsonModel));
                //把服务端返回的信息转成字符串
                var str = Encoding.UTF8.GetString(returnInfo);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine($"服务端返回信息:{str},时间:{DateTime.Now.ToString()}");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine($"请问是否继续:继续 【y】,退出【n】");
                operation = Console.ReadLine();
            } while (operation == "y");
        }

        class Data {
            public Data(int id, string name) {
                this.ID = id;
                this.Name = name;
            }
            public int ID { get; set; }
            public string Name { get; set; }
        }
    }

演示:

先启动服务端的程序,然后启动客户端的程序,客户端按任意键发送数据:

客户端发送数据后服务端会接收到数据,并返回相应的处理信息:

此时也可以打开浏览器,访问服务端,但由于不是post请求,返回异常信息:

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
下面是一个使用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和内容。然后构建响应内容,并将其发送回客户端。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值