码迷,mamicode.com
首页 > Web开发 > 详细

监听指定端口数据交互(HttpListenerContext )

时间:2016-01-27 21:08:59      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

以前的项目中的,拿来贴贴

场景:同步第三方数据(指定时间间隔,否则不满足,因为需要处理粘包问题,改篇未实现)

技术分享

主要内容四个文件;下面分别说下每个文件的功能。

1.HttpRequestManager.cs顾名思义,HttpRequest

public class HttpRequestManager
    {
        int _sDefaultLen = 102400;

        public virtual void OnHttpRequest(object context)
        {
            HttpListenerContext hltc = context as HttpListenerContext;
            if (hltc.Request.QueryString["cmd"] == null)
            {
                try
                {
                    //反馈给第三方平台 无CMD关键字
                    ReSendMsgService.SendResponse(hltc, "无CMD关键字");
                }
                catch (Exception ex)
                {
                     MyLog.WriteLog("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "返回给第三方无CMD关键字失败" + ex.Message);
                }
                //记录本地日志
                 MyLog.WriteLog("对象:OnHttpRequest:无CMD关键字,请联系第三方平台");
                return;
            }
            string sCmd = hltc.Request.QueryString["cmd"].ToUpper();
            switch (sCmd)
            {
                case "SUBMITPOLICY":
                    //指定接收方法
                     MyLog.WriteLog("对象:指令通过,当前指令为SUBMITPOLICY");
                    OnReceivPolisy(hltc);
                    break;
                default:
                    //反馈第三方平台,并记录本地日志 ,cmd指令错误 您的请求不被识别
                    try
                    {
                        ReSendMsgService.SendResponse(hltc, "PifRecvAgent 您的请求不被识别," + sCmd);
                    }
                    catch (Exception ex)
                    {
                         MyLog.WriteLog("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "返回给第三方PifRecvAgent 您的请求不被识别失败" + ex.Message);
                    }
                     MyLog.WriteLog("对象:OnHttpRequest: 第三方平台的请求不被识别");
                    break;
            }
        }

        //接收,解析方法
        void OnReceivPolisy(HttpListenerContext hltc)
        {
            byte[] buffer = new byte[_sDefaultLen];
            Stream stream = hltc.Request.InputStream;
            int sLen = 0;
            int sIndex = 0;

            while ((sIndex = stream.Read(buffer, sLen, 512)) != 0)
                sLen += sIndex;

            if (sLen < 1)
            {
                //反馈给第三方,并记录本地日志
                try
                {
                    ReSendMsgService.SendResponse(hltc, "Post的数据为空.");
                }
                catch (Exception ex)
                {
                    GLOBAL.MyLog.WriteLog("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "返回给第三方Post的数据为空失败" + ex.Message);
                }
                 MyLog.WriteLog("对象:OnReceivPolisy: Post的数据为空.");
            }
            //解析、入库
            bool jxbl = RelePolicyBuffer(buffer, buffer.Length);
            if (!jxbl)//XML解析失败
            {
                try
                {
                    //发送指令给第三方
                    ReSendMsgService.SendResponse(hltc, "XML结构解析失败");
                }
                catch (Exception ex)
                {
                     MyLog.WriteLog("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "返回给第三方XML结构解析失败失败" + ex.Message);
                }
            }
            //否则发送0给第三方
            try
            {
                ReSendMsgService.SendResponse(hltc, new byte[] { 0x30 });
            }
            catch (Exception ex)
            {
                 MyLog.WriteLog("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "返回给第三方 0 失败" + ex.Message);
            }
        }
        int r = 1;
        //解析入库方法
        bool RelePolicyBuffer(byte[] buffer, int bLen)
            {
        //此处为解析xml的脚本,省略,,,,,,,xmltextreader方式解析,单向只读
    
            }

    }
}
        

2.ReSendMessage.cs实现(接受结果之后给第三方返回接受结果信息)

/// <summary>
    /// /将响应结果反馈第三方,否则第三方默认失败,如此将延迟发送时间
    /// </summary>
    public class ReSendMsgService
    {

        #region SendResponse 给请求发发送应答
        public static bool SendResponse(HttpListenerContext ctx, string sErr)
        {
            byte[] buf = Encoding.Default.GetBytes(sErr);
            return SendResponse(ctx, 200, buf);
        }

        public static bool SendResponse(HttpListenerContext ctx, byte[] buf)
        {
            return SendResponse(ctx, 200, buf);
        }

        public static bool SendResponse(HttpListenerContext ctx, int nStatusCode, byte[] buf)
        {
            try
            {
                ctx.Response.StatusCode = nStatusCode;
                ctx.Response.ContentLength64 = buf.Length;
                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                return true;
            }
            catch (Exception ex)
            {

            }
            return false;
        }
        #endregion

    }

3.ThreadEntrustManager.cs类,用于监听器的初始化,见代码

/// <summary>
    /// 委托方法类
    /// </summary>
    public class ThreadEntrustManager
    {
        protected HttpListener _listener;
        Thread _ListenerThread;
        bool _bThreadLoop;
        string url;
        static string _ListenerUrls = XmlHelp.GetXmlNode("LocalListenUrl").InnerText;
        string[] _ListenerUrlsArray = _ListenerUrls.Split(;);

        public void ListenerStart()
        {
            if (_ListenerUrlsArray.Length > 0)
            {
                _listener = new HttpListener();
                _bThreadLoop = true;
                foreach (string strUrl in _ListenerUrlsArray)
                {
                    url = strUrl;
                    _listener.Prefixes.Add(url);//添加监听前缀对象
                }
                _listener.Start();
                 MyLog.WriteLog("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  start listening...");
                _ListenerThread = new Thread(new ThreadStart(ThreadFunction));
                _ListenerThread.Start();

            }
            else
            {
                _bThreadLoop = false;
               //日志
            }
        }

        void ThreadFunction()
        {
            while (_bThreadLoop)
            {
                try
                {
                     HttpListenerContext hltc = _listener.GetContext();
                    ThreadPool.QueueUserWorkItem(new HttpRequestManager().OnHttpRequest, hltc); //线程池委托接收对象
                }
                catch (Exception ex)
                {
                    GLOBAL.MyLog.WriteLog(ex);
                    Trace.Fail("对象:ThreadFunction :An error occured in database access, details: " + ex.Message);
                }
            }
        }

        public void ListenerClose()
        {
            _ListenerThread.Abort();
            _bThreadLoop = false;
            _listener.Close();
        }

    }

4.MainManager.cs主方法,程序启动时初始化调用

/// <summary>
    /// 主函数方法类
    /// </summary>
    public class MainManager
    {
        /// <summary>
        /// 主方法 开始是方法
        /// </summary>
        public static void MainStart()
        {
            try
            {
                _ListenerStart();
            }
            catch (Exception ex)
            {
               //记录异常日志信息
            }
        }


        public static void _ListenerStart()
        {
            ThreadEntrustManager manager = new ThreadEntrustManager();
            manager.ListenerStart();
        }

        public static void Close()
        {
           new ThreadEntrustManager().ListenerClose();
        }

    }

 

监听指定端口数据交互(HttpListenerContext )

标签:

原文地址:http://www.cnblogs.com/Tmc-Blog/p/5164292.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!