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

View: 19293|Reply: 0

[Source] .net uses HttpListener to listen to content and uses threads to respond to users to prevent blocking

[Copy link]
Posted on 12/17/2015 12:28:28 PM | | |
  1. /// <summary>
  2.         /// 开启监听
  3.         /// </summary>
  4.         private void Init()
  5.         {
  6.             try
  7.             {
  8.                 //指定身份验证 Anonymous匿名访问
  9.                 listeren.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
  10.                 //创建IP地址
  11.                 IPAddress address = IPAddress.Parse(Args.RunningArgs[0]);
  12.                 listeren.Prefixes.Add("http://" + address + ":" + Args.RunningArgs[1] + "/");
  13.                 listeren.Start();
  14.                 Thread threadlistener = new Thread(new ThreadStart(ThreadStartListener));
  15.                 threadlistener.IsBackground = true;
  16.                 threadlistener.Start();
  17.                 MessageBox.Show("监听成功");
  18.             }
  19.             catch (Exception ex)
  20.             {
  21.                 cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
  22.             }
  23.         }
  24.         /// <summary>
  25.         /// 监听连接线程
  26.         /// </summary>
  27.         private void ThreadStartListener()
  28.         {
  29.             while (true)
  30.             {
  31.                 //int i = 0;
  32.                 // 注意: GetContext 方法将阻塞线程,直到请求到达
  33.                 HttpListenerContext context = listeren.GetContext();
  34.                 //接收到请求,用线程去处理,防止阻塞
  35.                 Thread subThread = new Thread(new ParameterizedThreadStart((currContext) =>
  36.                 {
  37.                     int i = 0;
  38.                     var request = (HttpListenerContext)currContext;
  39.                     try
  40.                     {
  41.                         //post请求
  42.                         if (request.Request.HttpMethod.ToLower().Equals("post"))
  43.                         {
  44.                             this.Dispatcher.Invoke(new Action(() =>
  45.                             {
  46.                                 try
  47.                                 {
  48.                                     i = 1;
  49.                                     string QRcode = PostInput(request.Request);
  50.                                     var data = Convert.FromBase64String(QRcode);
  51.                                     BitmapImage bmp = new BitmapImage();
  52.                                     bmp.BeginInit();
  53.                                     bmp.StreamSource = new MemoryStream(data);
  54.                                     bmp.EndInit();
  55.                                     codeimg.Source = bmp;
  56.                                     Writer("success", request);
  57.                                     return;
  58.                                 }
  59.                                 catch (Exception ex)
  60.                                 {
  61.                                     Writer("img_error", request);
  62.                                     cfg.Logs.Add(new LogClass { LogStr = "HttpListener error", ExInfo = ex });
  63.                                     return;
  64.                                 }
  65.                             }));
  66.                         }
  67.                         else if (request.Request.HttpMethod.ToLower().Equals("get"))//get请求
  68.                         {
  69.                             Writer("get", request);
  70.                             return;
  71.                         }
  72.                         if (i.Equals(0))
  73.                         {
  74.                             Writer("no", request);
  75.                             return;
  76.                         }
  77.                     }
  78.                     catch (Exception)
  79.                     {
  80.                         Writer("error", request);
  81.                         return;
  82.                     }
  83.                 }));
  84.                 subThread.Start(context);  

  85.             }
  86.         }
  87.         /// <summary>
  88.         /// HttpListener接收post请求
  89.         /// </summary>
  90.         /// <param name="request"></param>
  91.         /// <returns></returns>
  92.         private string PostInput(HttpListenerRequest request)
  93.         {
  94.             try
  95.             {
  96.                 System.IO.Stream s = request.InputStream;
  97.                 int count = 0;
  98.                 byte[] buffer = new byte[1024];
  99.                 StringBuilder builder = new StringBuilder();
  100.                 while ((count = s.Read(buffer, 0, 1024)) > 0)
  101.                 {
  102.                     builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
  103.                 }
  104.                 s.Flush();
  105.                 s.Close();
  106.                 s.Dispose();
  107.                 return builder.ToString();
  108.             }
  109.             catch (Exception ex)
  110.             { throw ex; }
  111.         }
  112.         /// <summary>
  113.         /// 响应内容
  114.         /// </summary>
  115.         /// <param name="str"></param>
  116.         /// <param name="context"></param>
  117.         public void Writer(string str, HttpListenerContext context)
  118.         {
  119.             HttpListenerRequest request = context.Request;
  120.             HttpListenerResponse response = context.Response;
  121.             // 构造回应内容
  122.             string responseString = str;
  123.             // 设置回应头部内容,长度,编码
  124.             response.ContentLength64
  125.                 = System.Text.Encoding.UTF8.GetByteCount(responseString);
  126.             response.ContentType = "text/html; charset=UTF-8";
  127.             // 输出回应内容
  128.             System.IO.Stream output = response.OutputStream;
  129.             System.IO.StreamWriter writer = new System.IO.StreamWriter(output);
  130.             writer.Write(responseString);
  131.             // 必须关闭输出流
  132.             writer.Close();
  133.         }
Copy code






Previous:HttpListener receives the post request
Next:If there is return, try catch finally the execution order
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