zoukankan      html  css  js  c++  java
  • c# HttpListener 使用

    与 IIS 上发布网站相比,使用 HttpListener 编程的程序更加轻量化,易于发布和更新。配合 Thread 或 Task 类也可满足一定的并发。

    https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httplistener?view=netframework-4.7.2

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Net;
    using System.Threading;
    using System.IO;
    //https://docs.microsoft.com/zh-cn/dotnet/api/system.net.httplistener?view=netframework-4.7.2
    
    namespace WebServer
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    using (HttpListener listener = new HttpListener())
                    {
                        listener.Prefixes.Add("http://localhost:8888/");
                        listener.Start();
                        Console.WriteLine("开始监听");
                        while (true)
                        {
                            try
                            {
                                HttpListenerContext context = listener.GetContext();//阻塞
                                HttpListenerRequest request = context.Request;
                                string postData = new StreamReader(request.InputStream).ReadToEnd();
                                Console.WriteLine("收到请求:" + postData);
                                HttpListenerResponse response = context.Response;//响应
                                string responseBody = "响应";
                                response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody);
                                response.ContentType = "text/html; Charset=UTF-8";
                                //输出响应内容
                                Stream output = response.OutputStream;
                                using (StreamWriter sw = new StreamWriter(output))
                                {
                                    sw.Write(responseBody);
                                }
                                Console.WriteLine("响应结束");
                            }
                            catch (Exception err)
                            {
                                Console.WriteLine(err.Message);
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine("程序异常,请重新打开程序:" + err.Message);
                }
            }
        }
    }
  • 相关阅读:
    foxmail邮箱在代理环境下不能使用解决方法。
    Win7下IE8无法打开https类型的网站解决方法笔记
    重新注册IE组件
    Web开发者的六个代码调试平台
    仿Material UI框架的动画特效
    JS几种数组遍历方式以及性能分析对比
    js 函数提升和变量提升
    彻底掌握this,call,apply
    深入理解requestAnimationFrame
    基于iscroll.js实现下拉刷新和上拉加载特效
  • 原文地址:https://www.cnblogs.com/aitong/p/11642131.html
Copyright © 2011-2022 走看看