This article is a mirror article of machine translation, please click here to jump to the original article.

View: 21482|Reply: 0

[Source] net uses the HttpListener listening port

[Copy link]
Posted on 12/16/2015 3:32:24 PM | | |
  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.         }
Copy code






Previous:WPF reads and writes config files
Next:.net converts word documents into pdf files
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com