C# 監聽HTTP請求(遇到的一些問題)


先把代碼放在這里,下面再詳細解說: 

復制代碼
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Oracle.DataAccess.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace ConsoleApplication1
{
    class Program
    {
        static Object o = new object();
        static void Main(string[] args)
        {
            HttpListener listerner = new HttpListener();
            while (true)
            {
                try
                {
                    listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份驗證 Anonymous匿名訪問
                    listerner.Prefixes.Add("http://127.0.0.1:1500/Service/");
                    listerner.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("服務啟動失敗...");
                    break;
                }
                Console.WriteLine("服務器啟動成功.......");

                //線程池
                int minThreadNum;
                int portThreadNum;
                int maxThreadNum;
                ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
                ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
                Console.WriteLine("最大線程數:{0}", maxThreadNum);
                Console.WriteLine("最小空閑線程數:{0}", minThreadNum);
                //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);

                Console.WriteLine("\n\n等待客戶連接中。。。。");
                while (true)
                {
                    //等待請求連接
                    //沒有請求則GetContext處於阻塞狀態
                    HttpListenerContext ctx = listerner.GetContext();

                    ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
                }
                //listerner.Stop();
            }

            Console.ReadKey();
        }

        static void TaskProc(object o)
        {
            HttpListenerContext ctx = (HttpListenerContext)o;

            ctx.Response.StatusCode = 200;//設置返回給客服端http狀態代碼

            //接收Get參數
            string type = ctx.Request.QueryString["type"];
            string userId = ctx.Request.QueryString["userId"];
            string password = ctx.Request.QueryString["password"];
            string filename = Path.GetFileName(ctx.Request.RawUrl);
            string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文亂碼
            //進行處理
            Console.WriteLine("收到數據:" + userName);
            
            //接收POST參數
            Stream stream = ctx.Request.InputStream;
            System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
            String body = reader.ReadToEnd();
            Console.WriteLine("收到POST數據:" + HttpUtility.UrlDecode(body));
            Console.WriteLine("解析:" + HttpUtility.ParseQueryString(body).Get("userName"));

            //使用Writer輸出http響應代碼,UTF8格式
            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream,Encoding.UTF8))
            {
                writer.Write("處理結果,Hello world<br/>");
                writer.Write("數據是userId={0},userName={1}", userId, userName);
                writer.Close();
                ctx.Response.Close();
            }
        }

    }

}
復制代碼

 

1.可通過HttpUtility.UrlDecode對傳入的參數進行解碼,防止中文亂碼

2.StreamWriter必須使用UTF8格式,防止中文亂碼

3.微軟提供的HttpListener默認不能接收POST參數,所以需要自己去解析,上面已實現

4.界面可通過form的post方式直接提交數據

注意:
1.中文亂碼問題
   在客戶端采用如下形式
   String tmp   =   java.net.URLEncoder.encode(userName,   "utf-8");   //防止中文亂碼
   服務器端
    string filename = Path.GetFileName(ctx.Request.RawUrl);
   string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文亂碼
 
   服務器端需要引入: using System.Web;
   此時可能提示找不到庫,則在項目右鍵添加引用 找到 System.Web.dll勾選即可
2.[System.Net.HttpListenerException] = {"拒絕訪問。"}問題
   如果是win7或者win8,在cmd.exe上右鍵,以管理員身份運行,然后執行下面的命令
   netsh http add urlacl url=http://本機IP:1500/ user=用戶名(如Administrator)
 
   這個可以用代碼解決:
  
 public  void AddAddress(string address)
        {
            try
            {
                AddAddress(address, Environment.UserDomainName, Environment.UserName);
            }
            catch (Exception ex) { }
        }

        public void AddAddress(string address, string domain, string user)
        {
            string argsDll = String.Format(@"http delete urlacl url={0}", address);
            string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);
            ProcessStartInfo psi = new ProcessStartInfo("netsh", argsDll);
            psi.Verb = "runas";
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;
            Process.Start(psi).WaitForExit();//刪除urlacl
            psi = new ProcessStartInfo("netsh", args);
            psi.Verb = "runas";
            psi.CreateNoWindow = true;
            psi.WindowStyle = ProcessWindowStyle.Hidden;
            psi.UseShellExecute = false;
            Process.Start(psi).WaitForExit();//添加urlacl
        }

用法:AddAddress("http://127.0.0.1:1500/Service/Setup/");,同時啟動程序的要用管理員權限運行

   
3.記得關閉防火牆,或者只開放指定端口,步驟如下:
        step1、點擊控制面板

  
  step2、選擇windows防火牆,點擊高級設置
  
  step3、在彈出的“高級安全windows防火牆”點擊“入站規則”,在右側“操作”欄點擊“入站規則”下的“新建規則…”,此時會彈出一個窗口讓你設置。剩下的就非常傻瓜化了。
  
  step4、彈出“新建入站規則向導”-規則類型-選中“端口”,點擊下一步。選擇規則應用的協議“TCP/UDP”如果是TCP你就選擇TCP,UDP就選擇UDP。再勾選“特定本地端口”在文本框輸入您想開放的端口號(例如1521)。
  
  step5、點擊下一步,到“連接符合指定條件時應該進行什么操作?”選擇“允許連接”。點擊下一步到“配置文件”何時應用該規則,勾選“域”、“專用”、“公用”點擊下一步。
  
  step6、配置規則名稱,隨便輸入你自己認為好記的規則名稱即可。

4.你可能還會遇到下面這個問題:HTTP Error 503

如果你運行程序的電腦遇到了這個問題,就這樣把你上面的ip改成+號;例如:http://127.0.0.1:1500/Service/Setup/改成http://+:1500/Service/Setup/ 

記住AddAddress和listerner.Prefixes.Add里的ip都要改

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM