监听指定端口数据交互(HttpListenerContext )
很怀念以前做机票的日子,,,,可惜回不去
以前的项目中的,拿来贴贴
场景:同步第三方数据,监听指定地址(指定时间间隔,否则不满足,因为需要处理粘包问题,改篇未实现)

主要内容四个文件;下面分别说下每个文件的功能。
1.HttpRequestManager.cs顾名思义,HttpRequest
public class HttpRequestManager
{
int _sDefaultLen = ; 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 = ;
int sIndex = ; while ((sIndex = stream.Read(buffer, sLen, )) != )
sLen += sIndex; if (sLen < )
{
//反馈给第三方,并记录本地日志
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 = ;
//解析入库方法
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, , buf);
} public static bool SendResponse(HttpListenerContext ctx, byte[] buf)
{
return SendResponse(ctx, , 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, , 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 > )
{
_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 )的更多相关文章
- linux: 获取监听指定端口的进程PID
在 linux 下经常需要杀死(重启)监听某端口的进程, 因此就写了一个小脚本, 通过 ss 命令获取监听制定端口的进程 PID, 然后通过 kill 命令结束掉进程: #!/bin/sh # set ...
- 剥开比原看代码03:比原是如何监听p2p端口的
作者:freewind 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockchai ...
- Oracle 11g RAC 环境下单实例非缺省监听及端口配置
如果在Oracle 11g RAC环境下使用dbca创建单实例数据库后,Oracle会自动将其注册到缺省的1521端口及监听器.大多数情况下我们使用的为非缺省监听器以及非缺省的监听端口.而且在Orac ...
- .Net客户端监听ZooKeeper节点数据变化
一个很简单的例子,用途是监听zookeeper中某个节点数据的变化,具体请参见代码中的注释 using System; using System.Collections.Generic; using ...
- Android 监听ContentProvider的数据改变
今天介绍一下怎么监听ContentProvider的数据改变,主要的方法是:getContext().getContentResolver().notifyChange(uri,null),这行代码是 ...
- 普通用户从非80端口启动tomcat,通过端口转发监听80端口
linux下小于1024的端口都需要root去绑定. root权限启动tomcat是不明智的,可以使用非root权限启动tomcat监听8080端口,然后利用端口转发实现对80端口的监听. 端口转发: ...
- 【网络通信】服务器端Socket监听80端口,建立连接传输数据时也是使用的80端口么?
1. 服务器端Socket监听80端口,建立连接传输数据时也是使用的80端口么? 答:对.建立连接时服务器会分配一个新的Socket,但是用的源端口号还是80端口.套接字是由协议类型.源IP.目的IP ...
- Tomcat监听443端口的方法
当我们需要更安全的访问网站的时候就会选择使用https协议,而https协议默认的端口号为443端口,这就是我们为什么向让Tomcat监听在443端口的原因,因为监控在非80端口和443端口的web服 ...
- 配置Tomcat监听80端口、配置Tomcat虚拟主机、Tomcat日志
6月27日任务 16.4 配置Tomcat监听80端口16.5/16.6/16.7 配置Tomcat虚拟主机16.8 Tomcat日志扩展邱李的tomcat文档 https://www.linuser ...
随机推荐
- Distinct Substrings
spoj694:http://www.spoj.com/problems/DISUBSTR/ 题意:给以一个串,求这个串的所有不同子串的个数. 题解:第一次接触后缀数组,这里可以转化成,求所有子串后缀 ...
- 【zz】C++中struct与class的区别
转载来源:http://blog.sina.com.cn/s/blog_48f587a80100k630.html C++中的struct对C中的struct进行了扩充,它已经不再只是一个包含不同数据 ...
- 孤陋寡闻又一遭:ReportEvent API函数(有微软Service官方例子为例)
API 详解: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363679(v=vs.85).aspx 使用例子: https: ...
- JavaScript高级程序设计7.pdf
function类型 每个函数都是function类型的实例,函数是对象,函数名是指向对象的指针 function sum(num1,num2) { return num1+num2; } //等价于 ...
- 一个awk命令的demo
/prefix_* | awk -F'\x3' '{print $2}' | awk -F'\x2' '{for(i=0; i<NF; i++)print $i}'> ~/20140819 ...
- 在浏览器中简单输入一个网址,解密其后发生的一切(http请求的详细过程)
在浏览器中简单输入一个网址,解密其后发生的一切(http请求的详细过程) 原文链接:http://www.360doc.com/content/14/1117/10/16948208_42571794 ...
- linux上安装rar解压软件
描述:Linux默认自带ZIP压缩,最大支持4GB压缩,RAR的压缩比大于4GB. -------------------------------------------------- 下载 # wg ...
- 获取文件路径 分类: WinForm 2014-07-25 14:27 103人阅读 评论(0) 收藏
//可获得当前执行的exe的文件名. string str1 =Process.GetCurrentProcess().MainModule.FileName; //获取和设置当前目录(即该进程从中启 ...
- 【设计模式 - 10】之外观模式(Facade)
1 模式简介 外观模式隐藏了系统的复杂性,并向客户端提供了一个可以访问系统的接口.外观模式往往涉及到一个类,这个类提供了客户端请求的简化方法和对现有系统类方法的委托调用.外观模式使得系统中的 ...
- C# 打开PPT文件另存为PPTX
/// <summary> /// rename PPT /// </summary> private static void renamePPT() { //add refe ...