C# 利用HttpListener监听处理Http请求

C# 利用HttpListener监听处理Http请求

 (2014-05-15 11:25:11)

转载

 分类: C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

using System.Net;

using System.Net.Sockets;

using System.IO;

using System.Xml.Serialization;

using System.Threading;

using System.Web;

namespace ConsoleApplication3

{

    class Program

    {

        static void Main(string[] args)

        {

            try

            {

                HttpListener listerner = new HttpListener();

                {

                    for (; true; )

                    {

                        try

                        {

                            Console.Write("请输入服务器IP地址:");

                            string ip = Console.ReadLine();

 

                            listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问

                            listerner.Prefixes.Add("http://" + ip + ":1500/AnsweringMachineService/");

 

                            // listerner.Prefixes.Add("http://localhost/web/");

                            listerner.Start();

                        }

                        catch (Exception e)

                        {

                            Console.WriteLine("未能成功连接服务器.....");

                            listerner = new HttpListener();

                            continue;

                        }

                        break;

                    }

                    Console.WriteLine("服务器启动成功.......");

 

                    int maxThreadNum, portThreadNum;

 

                    //线程池

                    int minThreadNum;

                    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);

                    }

                    con.Close();

                    listerner.Stop();

                }

            }

            catch (Exception e)

            {

                Console.WriteLine(e.Message);

                Console.Write("Press any key to continue . . . ");

                Console.ReadKey( );

            }

 

        }

 

        static void TaskProc(object o)

        {

            HttpListenerContext ctx = (HttpListenerContext)o;

 

            ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码

       

            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");//避免中文乱码

 

    //进行处理

            

            //使用Writer输出http响应代码

            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream))

            {

                writer.Write(“处理结果”);

                writer.Close();

                ctx.Response.Close();

            }

        }

    }

}

 

 

 

Android客户端:

public static void Register(final Handler handler, final Context context,

final String userId, final String userName,final int groupId, final String password){

new Thread(new Runnable(){

       public void run() {

        if(!CommonTools.checkNetwork(context)){

        Message msg = new Message();

        msg.what = Signal.NETWORK_ERR;

        handler.sendMessage(msg);

        return;

        }

       

        try {  

        String content = "";

        String tmp   =   java.net.URLEncoder.encode(userName,   "utf-8");   //防止中文乱码

        URL url = new URL(URL+"?type=Register&userId="+userId+"&password="+password+"&groupId="+groupId+"&userName="+tmp);   

               // HttpURLConnection   

               HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();   

     

               if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {   

                     

                   InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");   

                   int i;   

                      

                   // read   

                   while ((i = isr.read()) != -1) {   

                       content = content + (char) i;   

                   }   

                   isr.close();     

               }   

               //disconnect   

               httpconn.disconnect();   

 

    } catch (Exception e) {

    e.printStackTrace();

    }

       }//run

}).start();//thread

}

 

注意:

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)

   

3.记得关闭防火墙,或者只开放指定端口,步骤如下:

        step1、点击控制面板

  
  step2、选择windows防火墙,点击高级设置
  
  step3、在弹出的“高级安全windows防火墙”点击“入站规则”,在右侧“操作”栏点击“入站规则”下的“新建规则…”,此时会弹出一个窗口让你设置。剩下的就非常傻瓜化了。
  
  step4、弹出“新建入站规则向导”-规则类型-选中“端口”,点击下一步。选择规则应用的协议“TCP/UDP”如果是TCP你就选择TCP,UDP就选择UDP。再勾选“特定本地端口”在文本框输入您想开放的端口号(例如1521)。
  
  step5、点击下一步,到“连接符合指定条件时应该进行什么操作?”选择“允许连接”。点击下一步到“配置文件”何时应用该规则,勾选“域”、“专用”、“公用”点击下一步。
  
  step6、配置规则名称,随便输入你自己认为好记的规则名称即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值