使用HttpListener在服务器端进行监听端口

   public class HttpPortListentHelp
    {
        private HttpListener _listener;

        //负责监听
        private Thread _threadWatchPort;

        public void StartListening()
        {
            try
            {
                _listener = new HttpListener();
                _listener.Prefixes.Add("http://10.45.17.136:10001/"); // 添加需要监听的url范围,Prefixes可添加多个
                _listener.Start(); //开始监听端口,接收客户端请求
                _threadWatchPort = new Thread(WatchPort);
                _threadWatchPort.Start();
            }
            catch (Exception ex)
            {

            }
        }

        private void WatchPort()
        {
            while (true)
            {
                try
                {
                    HttpListenerContext context = _listener.GetContext(); //等待请求连接,没有请求则GetContext处于阻塞状态
                    HttpListenerRequest request = context.Request; //客户端发送过来的消息
                    var reader = new StreamReader(request.InputStream);
                    var msg = reader.ReadToEnd();

                    string type = context.Request.QueryString["type"];
                    string userId = context.Request.QueryString["userId"];
                    string password = context.Request.QueryString["password"];
                    string filename = Path.GetFileName(context.Request.RawUrl);
                    string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码,HttpUtility需要添加   System.Web(在 System.Web.dll 中)

                    HttpListenerResponse response = context.Response;
                    context.Response.StatusCode = 200;//设置返回给客服端http状态代码
                    string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
                    byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                    response.ContentLength64 = buffer.Length;
                    Stream output = response.OutputStream;
                    output.Write(buffer, 0, buffer.Length); //服务端发送回消息给客户端
                    output.Close();
                }
                catch
                {
                    break;
                }
            }
        }

        public void CloseSocket()
        {
            if (_listener != null)
            {
                _listener.Stop();
                _listener.Close();
            }
            if (_threadWatchPort != null)
            {
                _threadWatchPort.Abort();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值