架构师_程序员_码农网

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

搜索
查看: 21324|回复: 0

[资料] net使用HttpListener监听端口

[复制链接]
发表于 2015-12-16 15:32:24 | 显示全部楼层 |阅读模式
  1. //log配置
  2.         Config cfg = new Config();
  3.         //HTTP监听
  4.         private HttpListener listeren = new HttpListener();
  5.         public QRcode()
  6.         {
  7.             InitializeComponent();
  8.         }
  9.         /// <summary>
  10.         /// 获取启动参数
  11.         /// </summary>
  12.         /// <param name="args"></param>
  13.         public void ShowEx(string[] args)
  14.         {
  15.             Args.RunningArgs = args;
  16.         }
  17.         /// <summary>
  18.         /// 开启监听
  19.         /// </summary>
  20.         private void Init()
  21.         {
  22.             try
  23.             {
  24.                 //指定身份验证 Anonymous匿名访问
  25.                 listeren.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  26.                 //创建IP地址
  27.                 IPAddress address = IPAddress.Parse(Args.RunningArgs[0]);
  28.                 listeren.Prefixes.Add("http://" + address + ":" + Args.RunningArgs[1] + "/");
  29.                 listeren.Start();
  30.                 Thread threadlistener = new Thread(new ThreadStart(ThreadStartListener));
  31.                 threadlistener.Start();
  32.                 //MessageBox.Show("监听成功");
  33.             }
  34.             catch (Exception ex)
  35.             {
  36.                 cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
  37.             }
  38.         }
  39.         /// <summary>
  40.         /// 监听连接线程
  41.         /// </summary>
  42.         private void ThreadStartListener()
  43.         {
  44.             try
  45.             {
  46.                 while (true)
  47.                 {
  48.                     // 注意: GetContext 方法将阻塞线程,直到请求到达
  49.                     HttpListenerContext context = listeren.GetContext();
  50.                     // 取得请求对象
  51.                     HttpListenerRequest request = context.Request;
  52.                     //响应
  53.                     Writer("ok", context);
  54.                 }
  55.             }
  56.             catch (Exception ex)
  57.             {
  58.                 cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
  59.             }
  60.         }
  61.         /// <summary>
  62.         /// 响应内容
  63.         /// </summary>
  64.         /// <param name="str"></param>
  65.         /// <param name="context"></param>
  66.         public void Writer(string str, HttpListenerContext context)
  67.         {
  68.             HttpListenerRequest request = context.Request;
  69.             Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl);
  70.             Console.WriteLine("Accept: {0}", string.Join(",", request.AcceptTypes));
  71.             Console.WriteLine("Accept-Language: {0}",
  72.                 string.Join(",", request.UserLanguages));
  73.             Console.WriteLine("User-Agent: {0}", request.UserAgent);
  74.             Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]);
  75.             Console.WriteLine("Connection: {0}",
  76.                 request.KeepAlive ? "Keep-Alive" : "close");
  77.             Console.WriteLine("Host: {0}", request.UserHostName);
  78.             Console.WriteLine("Pragma: {0}", request.Headers["Pragma"]);
  79.             // 取得回应对象
  80.             HttpListenerResponse response = context.Response;
  81.             // 构造回应内容
  82.             string responseString = str;
  83.             // 设置回应头部内容,长度,编码
  84.             response.ContentLength64
  85.                 = System.Text.Encoding.UTF8.GetByteCount(responseString);
  86.             response.ContentType = "text/html; charset=UTF-8";
  87.             // 输出回应内容
  88.             System.IO.Stream output = response.OutputStream;
  89.             System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
  90.             writer.Write(responseString);
  91.             // 必须关闭输出流
  92.             writer.Close();
  93.         }
  94.         private void Window_Loaded(object sender, RoutedEventArgs e)
  95.         {
  96.             try
  97.             {
  98.                 #region 开启日志
  99.                 string logPath = AppDomain.CurrentDomain.BaseDirectory + "log4net.config";
  100.                 LogHelper.SetConfig(new FileInfo(logPath));
  101.                 new Entity.LogClass().StartLogThread(ref cfg);
  102.                 cfg.Logs.Add(new LogClass { LogStr = "----------------------------------------------------------------------------------------------" });
  103.                 #endregion
  104.                 //开启监听
  105.                 Init();
  106.             }
  107.             catch (Exception ex)
  108.             {
  109.                 cfg.Logs.Add(new LogClass { LogStr = "Load parameter error", ExInfo = ex });
  110.             }
  111.         }
复制代码






上一篇:WPF读写config配置文件
下一篇:.net把word文档转换成pdf文件
码农网,只发表在实践过程中,遇到的技术难题,不误导他人。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

免责声明:
码农网所发布的一切软件、编程资料或者文章仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。如有侵权请邮件与我们联系处理。

Mail To:help@itsvse.com

QQ|小黑屋|架构师 ( 鲁ICP备14021824号-2 )|网站地图

GMT+8, 2026-1-2 21:42

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表