123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- namespace HPSocketCS.Extended
- {
- /// <summary>
- /// 程序运行状态
- /// </summary>
- public enum AppState
- {
- /// <summary>
- /// 启动中...
- /// </summary>
- Starting=0,
- /// <summary>
- /// 已启动
- /// </summary>
- Started=1,
- /// <summary>
- /// 停止中...
- /// </summary>
- Stoping=2,
- /// <summary>
- /// 已停止
- /// </summary>
- Stoped=3,
- /// <summary>
- /// 错误
- /// </summary>
- Error=4
- }
- /// <summary>
- /// 数据类型
- /// </summary>
- public enum DataType
- {
- /// <summary>
- /// 空数据
- /// </summary>
- None=0,
- /// <summary>
- /// 数组
- /// </summary>
- Array=1,
- /// <summary>
- /// 集合
- /// </summary>
- List=2,
- /// <summary>
- /// 文本信息
- /// </summary>
- Text=3,
- /// <summary>
- /// 序列化数据
- /// </summary>
- Serialization=4,
- /// <summary>
- /// 文件
- /// </summary>
- File=5,
- /// <summary>
- /// 显示窗体
- /// </summary>
- ShowForm=6,
- /// <summary>
- /// 推送消息
- /// </summary>
- PushMessage=7,
- /// <summary>
- /// 数据库信息处理
- /// </summary>
- SQLHelper=8,
- }
- /// <summary>
- /// 文件传输请求类型
- /// </summary>
- public enum FileRequestType
- {
- /// <summary>
- /// 上传
- /// </summary>
- Upload=0,
- /// <summary>
- /// 下载
- /// </summary>
- Download=1
- }
- /// <summary>
- /// 通信命令
- /// </summary>
- public enum TransferRequestCommand
- {
- /// <summary>
- /// 测试命令
- /// </summary>
- TestCommand=-1,
- /// <summary>
- /// 空命令
- /// </summary>
- EmptyCommand=0,
- /// <summary>
- /// 重要信息
- /// </summary>
- VitalInfo=1,
- /// <summary>
- /// 重要控制
- /// </summary>
- VitalControl = 2,
- /// <summary>
- /// 返回结果
- /// </summary>
- VitalControlOK=3,
- /// <summary>
- /// 文件传输
- /// </summary>
- FileTransfer=1000,
- /// <summary>
- /// 发送信息
- /// </summary>
- Message = 1001,
- /// <summary>
- /// 打开文件传输
- /// </summary>
- OpenFileTransfer = 1002,
- /// <summary>
- /// 关闭文件传输
- /// </summary>
- CloseFileTransfer = 1003,
- /// <summary>
- /// 上传用户头像
- /// </summary>
- UploadAvatar = 1004,
- /// <summary>
- /// 下载用户头像
- /// </summary>
- DownloadAvatar = 1005,
- /// <summary>
- /// 上传文件
- /// </summary>
- UploadFile = 1006,
- /// <summary>
- /// 下载文件
- /// </summary>
- DownloadFile = 1007,
- /// <summary>
- /// 获取文件信息
- /// </summary>
- GetFileInfo = 1008,
- /// <summary>
- /// 获取相片备份路径
- /// </summary>
- GetbackupPath = 1009,
- /// <summary>
- /// 获取相片保存路径
- /// </summary>
- GetSavePath = 1010,
- /// <summary>
- /// 上传客人头像
- /// </summary>
- UploadCustomersAvatar = 1011,
- /// <summary>
- /// 下载客人头像
- /// </summary>
- DownloadCustomersAvatar = 1012,
- /// <summary>
- /// 获取服务器软件信息,1.服务器ID 一搬为Lock短ID 2.类型 是总服务器还是分店服务器 3.软件业务类型 4.功能类型 5.服务器版本号
- /// </summary>
- GetServerSoftwareInfo = 1013,
- /// <summary>
- /// 获取数据库连接字符串
- /// </summary>
- GetDataConne = 1014,
- /// <summary>
- /// 获取相片保存路径集合 用于客户端读取订单相片
- /// </summary>
- GetSavePhotoPathList = 1015,
- /// <summary>
- /// 获取服务器时间 带有服务器版本号 用于检查客户端是否需要更新
- /// </summary>
- ServerDateTime = 1016,
- /// <summary>
- /// 删除文件
- /// </summary>
- DeleteFile = 1017,
- /// <summary>
- /// 生成缩略图
- /// </summary>
- GenerateThumbnails = 1018,
- /// <summary>
- /// 导入相片请求
- /// </summary>
- ImportPhotos = 1019,
- /// <summary>
- /// 选片请求
- /// </summary>
- SelectPhotos = 1020,
- /// <summary>
- /// 查看相片请求
- /// </summary>
- LookPhotos = 1021,
- /// <summary>
- /// 更新订单请求
- /// </summary>
- UpdateOrder = 1022,
- /// <summary>
- /// 获取最新客户端皮肤图片
- /// </summary>
- GetUpdateClientSkinImage = 1023,
- /// <summary>
- /// 删除原始相片
- /// </summary>
- DeleteOriginalPhoto = 1024,
- /// <summary>
- /// 删除备份相片
- /// </summary>
- DeleteBackupPhoto = 1025,
- /// <summary>
- /// 获取客户端列表
- /// </summary>
- GetClientList = 1026,
- /// <summary>
- /// 刷新客户连接
- /// </summary>
- RefreshClientList = 1027,
- /// <summary>
- /// 获取数据
- /// </summary>
- GetBigData = 1028,
- /// <summary>
- /// 获取文件列表
- /// </summary>
- GeTFileList = 1029,
- /// <summary>
- /// 获取目录列表
- /// </summary>
- GetDirectoryList = 1030,
- /// <summary>
- /// 删除目录
- /// </summary>
- DeleteDirectory = 1031,
- /// <summary>
- /// 获取备份记录
- /// </summary>
- GetBackupRecords=1032,
- /// <summary>
- /// 获取总店数据库备份记录
- /// </summary>
- GetMainShopBackupRecords=1033,
- /// <summary>
- /// 获取总店测试信息
- /// </summary>
- MainStoreTestInfo=1034,
- /// <summary>
- /// SQL数据库操作
- /// </summary>
- SQLHelperData=1035,
- /// <summary>
- /// 序例化数据传输
- /// </summary>
- SerializationData=1036,
- /// <summary>
- /// 安装数据库
- /// </summary>
- InstallationDatabase=1037,
- /// <summary>
- /// 升级数据库
- /// </summary>
- UpgradeDatabase = 1038,
- /// <summary>
- /// 刷新云服务器数据
- /// </summary>
- RefreshCloudServerData=1039,
- /// <summary>
- /// 云登录
- /// </summary>
- CloudLoginIP=1040,
- /// <summary>
- /// 提效软件信息
- /// </summary>
- SubmitSoftwareInfo=1041,
- /// <summary>
- /// 获取总店服务器软件信息
- /// </summary>
- GetMainStoreServerSoftwareInfo = 1042,
- /// <summary>
- /// 备份数据库
- /// </summary>
- BackupDatabase=1043,
- /// <summary>
- /// 客户端在线连接
- /// </summary>
- ClientOnlineConnection=1044,
- }
- /// <summary>
- /// SQLHelper请求类型
- /// </summary>
- public enum SQLHelperRequestType
- {
- /// <summary>
- /// 执行查询语句,返回DataSet
- /// </summary>
- QueryReturnDataSet= 0,
- /// <summary>
- /// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
- /// </summary>
- ExecuteScalar=1,
- /// <summary>
- /// 对连接执行 Transact-SQL 语句并返回受影响的行数。
- /// </summary>
- ExecuteNonQuery=2,
- /// <summary>
- /// 执行存储过程
- /// </summary>
- RunProcedure=3,
- /// <summary>
- /// 执行事务
- /// </summary>
- ExecuteSqlTran=4,
- /// <summary>
- /// 检查数据库连接 是否能正常连接数据
- /// </summary>
- ExistsSqlConn=5,
-
- }
- public delegate void DelegateExecuteThreadStart(ReturnResultObject argumentResult);
- public class CommonLibrary
- {
- public CommonLibrary() {
-
- }
- /// <summary>
- /// WebForm和WinForm通用的取当前根目录的方法
- /// </summary>
- public static string BasePath
- {
- get
- {
- System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
- //WebDev.WebServer visual studio web server
- //xxx.vhost Winform
- //w3wp IIS7
- //aspnet_wp IIS6
- string processName = p.ProcessName.ToLower();
- string retPath = System.Windows.Forms.Application.StartupPath;
- if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
- {
- if (System.Web.HttpContext.Current != null)
- retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
- else //当控件在定时器的触发程序中使用时就为空
- {
- retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
- }
- }
- return retPath;
- }
- }
- /// <summary>
- /// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
- /// </summary>
- /// <param name="directoryPath"></param>
- /// <returns></returns>
- public static string GetFullDirectoryPath(string directoryPath)
- {
- if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
- {
- directoryPath = directoryPath + "\\";
- }
- return directoryPath;
- }
- /// <summary>
- /// 全局ID
- /// </summary>
- /// <returns></returns>
- public static long GenerateId()
- {
- byte[] buffer = Guid.NewGuid().ToByteArray();
- return BitConverter.ToInt64(buffer, 0);
- }
- static string _ServerVersionNumber = "1.0";
- /// <summary>
- /// 服务器版本号
- /// </summary>
- public static string ServerVersionNumber
- {
- get { return CommonLibrary._ServerVersionNumber; }
- set { CommonLibrary._ServerVersionNumber = value; }
- }
- static string _ClientMarkID = "ServerHosts";
- /// <summary>
- /// 客户端标识ID
- /// </summary>
- public static string ClientMarkID
- {
- get { return CommonLibrary._ClientMarkID; }
- set { CommonLibrary._ClientMarkID = value; }
- }
- static string _ClientMarkName = "服务器主机";
- /// <summary>
- /// 客户端标识名称
- /// </summary>
- public static string ClientMarkName
- {
- get { return CommonLibrary._ClientMarkName; }
- set { CommonLibrary._ClientMarkName = value; }
- }
- static string _LoginUsername = "未知用户";
- /// <summary>
- ///登录用户名
- /// </summary>
- public static string LoginUsername
- {
- get { return CommonLibrary._LoginUsername; }
- set { CommonLibrary._LoginUsername = value; }
- }
- private static string _HardwareCode = "HardwareCode";
- /// <summary>
- /// 硬件码
- /// </summary>
- public static string HardwareCode
- {
- get { return CommonLibrary._HardwareCode; }
- set { CommonLibrary._HardwareCode = value; }
- }
- #region 发送数据时的方法
- /// <summary>
- /// 获取发送数据时的头协议结构
- /// </summary>
- /// <param name="ConnId">连接ID</param>
- /// <param name="addedDataPtr">附加数据</param>
- /// <param name="dType">要发送的数据类型</param>
- /// <param name="requestCommand">请求命令</param>
- /// <param name="transportID">传输标识符</param>
- /// <param name="isTail">是否有协议尾信息</param>
- /// <returns></returns>
- public static TcpHeadInfo GetProtocolHeader(IntPtr ConnId, IntPtr addedDataPtr, DataType dType, TransferRequestCommand requestCommand, Int64 transportID, bool isTail = false)
- {
- HPSocketCS.Extended.ClientInfo ci = null;
- try
- {
- // IntPtr.Zero;
- // ci 就是accept里传入的附加数据了
- if (addedDataPtr != IntPtr.Zero)
- {
- ci = (HPSocketCS.Extended.ClientInfo)Marshal.PtrToStructure(addedDataPtr, typeof(HPSocketCS.Extended.ClientInfo));
- }
- }
- catch { }
- TcpHeadInfo protocolHeader = new TcpHeadInfo();
- protocolHeader.ConnId = ConnId.ToInt32();
- protocolHeader.Hostname = System.Net.Dns.GetHostName();
- protocolHeader.MsgDataType = (int)dType;
- protocolHeader.RequestCommand = (int)requestCommand;
- protocolHeader.IntactSize = 0;
- protocolHeader.ServerNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- protocolHeader.ClientMarkID = CommonLibrary.ClientMarkID;
- protocolHeader.ClientMarkName = CommonLibrary.ClientMarkName;
- protocolHeader.ServerVersionNumber = CommonLibrary.ServerVersionNumber;
- protocolHeader.LoginUsername = CommonLibrary.LoginUsername;
- protocolHeader.HardwareCode = CommonLibrary.HardwareCode;
- protocolHeader.TransportEnd = true;
- protocolHeader.TransportStart = true;
- protocolHeader.TransportID = transportID;
- protocolHeader.IsTail = isTail;
- if (ci != null)
- {
- protocolHeader.IPAddress = ci.IpAddress;
- protocolHeader.Port = ci.Port;
- }
- return protocolHeader;
- }
- /// <summary>
- /// 写日志 调试时使用
- /// </summary>
- /// <param name="txt">日志内容</param>
- /// <param name="fullPath">日志文件全路径</param>
- public static void WriteLogs(string txt)
- {
- try
- {
- string fullPath = BasePath + "\\Logs\\MainLogs\\"+DateTime.Now.ToString("yyyy-MM-dd")+".txt";
- if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(fullPath)))
- {
- System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fullPath));
- }
- using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, Encoding.UTF8))
- {
- sw.WriteLine("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "】" + txt);
- sw.Flush();
- sw.Close();
- }
- }
- catch { }
- }
- /// <summary>
- /// 自动拆包并加上包头 包尾
- /// </summary>
- /// <param name="packBytes">要拆分的数据包</param>
- /// <param name="pkgHeader">包头结构</param>
- /// <param name="maxPackSize">每包的最大大小</param>
- /// <returns>返回拆分后的数据包集合</returns>
- public static System.IO.BufferedStream AutoUnpackingAndAddPkgHeader(byte[] sendPackBytes, TcpHeadInfo pkgHeader, TcpTailInfo pkgTail, int maxPackSize)
- {
-
- // WriteLogs("压缩前的长度:" + packBytes.Length);
- byte[] packBytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataCompressionRetBytes(sendPackBytes);
- System.IO.MemoryStream retDataMstream = new System.IO.MemoryStream();
- System.IO.BufferedStream buffStream = new System.IO.BufferedStream(retDataMstream, Sdk.PacketBufferSize * 2);
- try
- {
- // WriteLogs("压缩后的长度:" + packBytes.Length);
- // byte[] tempbytes=HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(packBytes);
- // string tempstr = Encoding.UTF8.GetString(tempbytes, 0, tempbytes.Length);
- // WriteLogs("压缩后解压还原后的信息:"+tempstr);
- // List<byte[]> byteList = new List<byte[]>();
- pkgHeader.IntactSize = packBytes.Length;
- pkgHeader.ServerNowTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- // 包头大小
- int pkgHeaderSize = Marshal.SizeOf(pkgHeader);
- int pkgTailSize = 0;
- if (pkgHeader.IsTail)
- {
- pkgTailSize = Marshal.SizeOf(pkgTail);
- }
- //附加协议数据包大小
- int AppendPakSize = pkgHeaderSize + pkgTailSize;
- if (packBytes.Length + AppendPakSize <= maxPackSize)
- {
- pkgHeader.TransportStart = true;
- pkgHeader.TransportEnd = true;
- //包头数据
- byte[] pkgHeaderBytes = StructureToByte<TcpHeadInfo>(pkgHeader);
- // 组合最终发送的封包 (封包头封包体)
- byte[] sendBytes = null;
- if (pkgHeader.IsTail)
- {
- byte[] tailBytes = StructureToByte<TcpTailInfo>(pkgTail);
- sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, packBytes, tailBytes);
- tailBytes = null;
- }
- else
- {
- sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, packBytes, null);
- }
- buffStream.Write(sendBytes, 0, sendBytes.Length);
- //retDataMstream.Write(sendBytes, 0, sendBytes.Length);
- // byteList.Add(sendBytes);
- sendBytes = null;
- pkgHeaderBytes = null;
- }
- else
- {
- //每包大小
- int packSize = Convert.ToInt32(maxPackSize - AppendPakSize);
- //可拆包数
- int packCount = packBytes.Length / packSize;
- if (packBytes.Length % packSize > 0)
- {
- packCount = packCount + 1;
- }
- for (int i = 0; i < packCount; i++)
- {
- byte[] tempPackBytes = new byte[packSize];
- if (i == 0)
- {
- pkgHeader.TransportStart = true;
- pkgHeader.TransportEnd = false;
- }
- else
- {
- pkgHeader.TransportStart = false;
- pkgHeader.TransportEnd = false;
- }
- if (i + 1 == packCount)
- {
- pkgHeader.TransportEnd = true;
- tempPackBytes = new byte[packBytes.Length - packSize * i];
- }
- Array.Copy(packBytes, i * packSize, tempPackBytes, 0, tempPackBytes.Length);
- //包头数据
- byte[] pkgHeaderBytes = StructureToByte<TcpHeadInfo>(pkgHeader);
- // 组合最终发送的封包 (封包头封包体)
- byte[] sendBytes = null;
- if (pkgHeader.IsTail)
- {
- byte[] tailBytes = StructureToByte<TcpTailInfo>(pkgTail);
- sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, tempPackBytes, tailBytes);
- tailBytes = null;
- }
- else
- {
- sendBytes = CommonLibrary.GetSendBuffer(pkgHeaderBytes, tempPackBytes, null);
- }
- buffStream.Write(sendBytes, 0, sendBytes.Length);
- //retDataMstream.Write(sendBytes, 0, sendBytes.Length);
- // byteList.Add(sendBytes);
- pkgHeaderBytes = null;
- sendBytes = null;
- }
- }
- }
- catch
- {
- }
- buffStream.Flush();
- buffStream.Position = 0;
- retDataMstream.Position = 0;
- Array.Clear(packBytes, 0, packBytes.Length);
- packBytes = null;
- //return byteList;
- return buffStream;
- }
- /// <summary>
- /// 由结构体转换为byte数组
- /// </summary>
- public static byte[] StructureToByte<T>(T structure)
- {
- int size = Marshal.SizeOf(typeof(T));
- byte[] buffer = new byte[size];
- IntPtr bufferIntPtr = Marshal.AllocHGlobal(size);
- try
- {
- Marshal.StructureToPtr(structure, bufferIntPtr, true);
- Marshal.Copy(bufferIntPtr, buffer, 0, size);
- }
- finally
- {
- Marshal.FreeHGlobal(bufferIntPtr);
- }
- return buffer;
- }
- /// <summary>
- /// 组合最终发送的封包 (封包头+封包体)
- /// </summary>
- /// <param name="headerBytes">封包头</param>
- /// <param name="bodyBytes">封包体</param>
- /// <returns></returns>
- public static byte[] GetSendBuffer(byte[] headerBytes, byte[] bodyBytes,byte[] tailBytes)
- {
- // IntPtr ptr = IntPtr.Zero;
- byte[] retBytes = null;
- try
- {
- int bufferSize = headerBytes.Length + bodyBytes.Length;
- if (tailBytes != null)
- {
- bufferSize= bufferSize + tailBytes.Length;
- }
- retBytes = new byte[bufferSize];
- // 拷贝包头到缓冲区首部
- Array.Copy(headerBytes, 0, retBytes, 0, headerBytes.Length);
- //Marshal.Copy(headerBytes, 0, ptr, headerBytes.Length);
- // 拷贝包体到缓冲区剩余部分
- Array.Copy(bodyBytes, 0, retBytes, headerBytes.Length, bodyBytes.Length);
-
- if (tailBytes != null)
- {
- // 拷贝包尾到缓冲区剩余部分
- Array.Copy(tailBytes, 0, retBytes, headerBytes.Length + bodyBytes.Length, tailBytes.Length);
-
- }
- return retBytes;
- }
- finally
- {
- headerBytes = null;
- bodyBytes = null;
- tailBytes = null;
- }
- }
-
- #endregion
- #region 接收数据时的方法
- /// <summary>
- /// 接收数据集合
- /// </summary>
- List<ReceiveData> ReceiveDataList = new List<ReceiveData>();
- /// <summary>
- /// 获取本次通信的收接数据处理对象 如果没有时返回null
- /// </summary>
- /// <param name="tcpInfo"></param>
- /// <returns></returns>
- public ReceiveData GetReceiveData(TcpHeadInfo tcpInfo)
- {
- ReceiveData retRData = null;
- lock (ReceiveDataList)
- {
- foreach (ReceiveData rData in ReceiveDataList)
- {
- if (rData.ReceiveRemoteClientInfo.ConnId == tcpInfo.ConnId && rData.ReceiveRemoteClientInfo.TransportID == tcpInfo.TransportID)
- {
- retRData = rData;
- break;
- }
- }
- return retRData;
- }
- }
- /// <summary>
- /// 添加接收数据处理对象
- /// </summary>
- /// <param name="rData"></param>
- public void AddReceiveData(ReceiveData rData)
- {
- lock (ReceiveDataList)
- {
- this.ReceiveDataList.Add(rData);
- }
- }
- /// <summary>
- /// 移除接收数据处理对象
- /// </summary>
- /// <param name="rData"></param>
- public void RemoveReceiveDataData(ReceiveData rData)
- {
- try
- {
- lock (ReceiveDataList)
- {
- ReceiveDataList.Remove(rData);
- }
- if (rData != null)
- {
- rData.Dispose();
- // rData.ReceiveDataMstream.Close();
- // rData.ReceiveDataMstream.Dispose();
- // rData.ReceiveDataMstream = null;
- rData = null;
- }
- }
- catch { }
- finally
- {
- System.GC.Collect();
- }
- }
- /// <summary>
- /// 清除所有无效连接资源
- /// </summary>
- /// <param name="connId"></param>
- public void ClearAllInvalidResource()
- {
- lock (ReceiveDataList)
- {
- int count = ReceiveDataList.Count;
- for (int i = 0; i < count; i++)
- {
- DispenseReceiveData(ReceiveDataList[i]);
- }
- ReceiveDataList.Clear();
- }
- }
- public void DispenseReceiveData(ReceiveData rData)
- {
- lock (ReceiveDataList)
- {
- ReceiveDataList.Remove(rData);
- if (rData != null)
- {
- /* rData.ReceiveDataMstream.Close();
- rData.ReceiveDataMstream.Dispose();
- rData.ReceiveDataMstream = null;*/
- rData.Dispose();
- rData = null;
- }
- }
- }
- /// <summary>
- /// 清除无效连接资源
- /// </summary>
- /// <param name="connId"></param>
- public void ClearInvalidConnectionResource(IntPtr connId)
- {
- try
- {
- List<ReceiveData> retRDatalist = new List<ReceiveData>();
- lock (ReceiveDataList)
- {
- foreach (ReceiveData rData in ReceiveDataList)
- {
- if (rData.ReceiveRemoteClientInfo.ConnId == connId.ToInt32())
- {
- retRDatalist.Add(rData);
- }
- }
- for (int i = 0; i < retRDatalist.Count; i++)
- {
- DispenseReceiveData(retRDatalist[i]);
- }
- retRDatalist.Clear();
- }
- }
- catch
- {
- }
- finally
- {
- System.GC.Collect();
- }
- }
- #endregion
- #region 客户端接收到的数据缓存处理方法
- Dictionary<Int64, ReceiveCacheBuffer> _ServerToClientCacheBufferList = new Dictionary<Int64, ReceiveCacheBuffer>();
- /// <summary>
- /// 收到服务发送回来的数据集合
- /// </summary>
- public Dictionary<Int64, ReceiveCacheBuffer> ServerToClientCacheBufferList
- {
- get { return _ServerToClientCacheBufferList; }
- set { _ServerToClientCacheBufferList = value; }
- }
- /// <summary>
- /// 获取收到的数据缓存区对象
- /// </summary>
- /// <param name="cid">数据传输标识符</param>
- /// <returns></returns>
- public ReceiveCacheBuffer GetReceiveCacheBuffer(Int64 cid)
- {
- lock (_ServerToClientCacheBufferList)
- {
- ReceiveCacheBuffer retCacheBuffer = null;
- if (_ServerToClientCacheBufferList.TryGetValue(cid, out retCacheBuffer))
- {
- return retCacheBuffer;
- }
- else
- {
- return retCacheBuffer;
- }
- }
- }
- /// <summary>
- /// 添加数据缓存区对象到集合中
- /// </summary>
- /// <param name="cid">数据传输标识符</param>
- /// <param name="rCacheBuffer"></param>
- public void AddCacheBufferToList(Int64 cid, ReceiveCacheBuffer rCacheBuffer)
- {
- lock (_ServerToClientCacheBufferList)
- {
- if (!this._ServerToClientCacheBufferList.ContainsKey(cid))
- {
- this._ServerToClientCacheBufferList.Add(cid, rCacheBuffer);
- }
- /* IntPtr ptrbytes = GetReceiveBytes(cid);
- if (ptrbytes != IntPtr.Zero) {
- Marshal.FreeHGlobal(ptrbytes);
- ptrbytes = IntPtr.Zero;
- }
- DataHeader dhead = new DataHeader();
- dhead.Length = bytes.Length;
- int bufferSize = bytes.Length+Marshal.SizeOf(dhead);
- byte[] dheadBytes = StructureToByte<DataHeader>(dhead);
- ptrbytes = Marshal.AllocHGlobal(bufferSize);
- // 拷贝头数据到缓冲区
- Marshal.Copy(dheadBytes, 0, ptrbytes, dheadBytes.Length);
- // 拷贝数据到缓冲区剩余部分
- Marshal.Copy(bytes, 0, ptrbytes + dheadBytes.Length, bytes.Length);
-
- _ServerToClientByteList.Add(cid, ptrbytes);
- bytes = null;*/
- }
- }
- /// <summary>
- /// 移除指定的数据缓存区对象
- /// </summary>
- /// <param name="cid"></param>
- public void RemoveServerToClientByteList(Int64 cid)
- {
- try
- {
- lock (_ServerToClientCacheBufferList)
- {
- try
- {
- ReceiveCacheBuffer rCacheBuffer = GetReceiveCacheBuffer(cid);
- if (rCacheBuffer != null)
- {
- rCacheBuffer.Dispose();
- rCacheBuffer = null;
- }
- }
- catch { }
- _ServerToClientCacheBufferList.Remove(cid);
- }
- }
- finally {
- System.GC.Collect();
- }
- }
- /// <summary>
- /// 清除所有数据缓存区对象
- /// </summary>
- public void ClearAllServerToClientByteList()
- {
- try
- {
- lock (_ServerToClientCacheBufferList)
- {
- foreach (long key in _ServerToClientCacheBufferList.Keys)
- {
- try
- {
- _ServerToClientCacheBufferList[key].Dispose();
- }
- catch { }
- }
- _ServerToClientCacheBufferList.Clear();
- }
- }
- finally
- {
- System.GC.Collect();
- }
- }
- #endregion
- /// <summary>
- /// 进程进度报告
- /// </summary>
- /// <param name="sumCount">运行总计数器</param>
- /// <param name="currentCount">当前进度值</param>
- /// <param name="msg">报告信息</param>
- public static void SetBackgroundWorker(long sumCount, long currentCount, string msg = "", System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- if (backgroundWorker != null)
- {
- try
- {
- int currentProgres = Convert.ToInt32(1000f / sumCount * currentCount);
- //WriteLogs("共 " + sumCount + " 字节 已接收 " + currentCount + " 字节 当前 " + currentProgres +" %");
- backgroundWorker.ReportProgress(currentProgres, msg);
- }
- catch { }
- }
- }
- /// <summary>
- /// 获取VC++ MD5
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string GetVCFileMD5(string filePath)
- {
- string retMd5Value = "";
- byte[] retByte = new byte[32];
- IntPtr bufferIntPtr_File = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
- if (Environment.Is64BitProcess)
- {
- if (VCMD5_X64.GetFileMD5(filePath, bufferIntPtr_File, 32) == 0)
- {
- System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr_File, retByte, 0, 32);
- retMd5Value = Encoding.UTF8.GetString(retByte);
- }
- }
- else
- {
- if (VCMD5_X86.GetFileMD5(filePath, bufferIntPtr_File, 32) == 0)
- {
- System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr_File, retByte, 0, 32);
- retMd5Value = Encoding.UTF8.GetString(retByte);
- }
- }
- System.Array.Clear(retByte, 0, retByte.Length);
- retByte = null;
- if (bufferIntPtr_File != IntPtr.Zero)
- {
- System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr_File);
- }
- return retMd5Value;
- }
- /// <summary>
- /// 获取VC++ MD5
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string GetVCByteMD5(byte[] bytes)
- {
- string retMd5Value = "";
- byte[] retByte = new byte[32];
- IntPtr lpBytes = System.Runtime.InteropServices.Marshal.AllocHGlobal(bytes.Length);
- System.Runtime.InteropServices.Marshal.Copy(bytes, 0, lpBytes, bytes.Length);
- IntPtr bufferIntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
- if (Environment.Is64BitProcess)
- {
- if (VCMD5_X64.GetByteMD5(lpBytes, bytes.Length, bufferIntPtr) == 0)
- {
- System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
- retMd5Value = Encoding.UTF8.GetString(retByte);
- }
- }
- else
- {
- if (VCMD5_X86.GetByteMD5(lpBytes, bytes.Length, bufferIntPtr) == 0)
- {
- System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
- retMd5Value = Encoding.UTF8.GetString(retByte);
- }
- }
- if (bufferIntPtr != IntPtr.Zero)
- {
- System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr);
- }
- if (lpBytes != IntPtr.Zero)
- {
- System.Runtime.InteropServices.Marshal.FreeHGlobal(lpBytes);
- }
- return retMd5Value;
- }
- /// <summary>
- /// 获取VC++ MD5
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public static string GetVCStringMD5(string str)
- {
- string retMd5Value = "";
- byte[] retByteUtf8 = Encoding.UTF8.GetBytes(str);
- string Gb2313 = Encoding.GetEncoding("gb2312").GetString(retByteUtf8);
- byte[] retByte = new byte[32];
- IntPtr bufferIntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(32);
- if (Environment.Is64BitProcess)
- {
- if (VCMD5_X64.GetStringMD5(Gb2313, bufferIntPtr, 32) == 0)
- {
- System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
- retMd5Value = Encoding.UTF8.GetString(retByte);
- }
- }
- else
- {
- if (VCMD5_X86.GetStringMD5(Gb2313, bufferIntPtr, 32) == 0)
- {
- System.Runtime.InteropServices.Marshal.Copy(bufferIntPtr, retByte, 0, 32);
- retMd5Value = Encoding.UTF8.GetString(retByte);
- }
- }
- if (bufferIntPtr != IntPtr.Zero)
- {
- System.Runtime.InteropServices.Marshal.FreeHGlobal(bufferIntPtr);
- }
- return retMd5Value;
- }
- /// <summary>
- /// 是否FIPS出错
- /// </summary>
- static bool isFIPSError = false;
- /// <summary>
- /// 获取文件的MD5值
- /// </summary>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static string GetMD5HashFromFile(byte[] byets)
- {
- try
- {
- if (!isFIPSError)
- {
- try
- {
- System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
- byte[] retVal = md5.ComputeHash(byets);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < retVal.Length; i++)
- {
- sb.Append(retVal[i].ToString("x2"));
- }
- byets = null;
- return sb.ToString();
- }
- catch //(Exception ex)
- {
- isFIPSError = true;
- return GetVCByteMD5(byets);
- //throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
- }
- }
- else
- {
- return GetVCByteMD5(byets);
- }
- }
- catch (Exception ex)
- {
- throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
- }
- }
- /// <summary>
- /// 获取文件的MD5值
- /// </summary>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static string GetMD5HashFromFile(string fileName)
- {
- try
- {
- if (!isFIPSError)
- {
- System.IO.FileStream file = null;
- try
- {
- file = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
- }
- catch (Exception ex)
- {
- throw new Exception("验证MD5时打开文件出失败:" + ex.Message);
- }
- try
- {
- System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
- byte[] retVal = md5.ComputeHash(file);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < retVal.Length; i++)
- {
- sb.Append(retVal[i].ToString("x2"));
- }
- System.Array.Clear(retVal, 0, retVal.Length);
- retVal = null;
- return sb.ToString();
- }
- catch //(Exception ex)
- {
- isFIPSError = true;
- return GetVCFileMD5(fileName);
- // throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
- }
- finally
- {
- file.Close();
- file.Dispose();
- }
- }
- else
- {
- return GetVCFileMD5(fileName);
- }
- }
- catch (Exception ex)
- {
- throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
- }
- }
- /// <summary>
- /// 验证两个MD5值是否相同
- /// </summary>
- /// <param name="md51"></param>
- /// <param name="md52"></param>
- /// <returns></returns>
- public static bool VerifyMd5Hash(string md51, string md52)
- {
- if (md51.Trim().ToUpper() == md52.Trim().ToUpper())
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- public class VCMD5_X86
- {
- [System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
- public static extern int GetStringMD5(string lpString, IntPtr pResult, int length);
- [System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
- public static extern int GetFileMD5(string lpFilepath, IntPtr pResult, int length);
- [System.Runtime.InteropServices.DllImport("lyfzMD5_x86.dll")]
- public static extern int GetByteMD5(IntPtr lpBytes, int nInputlen, IntPtr pResult);
- }
- public class VCMD5_X64
- {
- [System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
- public static extern int GetStringMD5(string lpString, IntPtr pResult, int length);
- [System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
- public static extern int GetFileMD5(string lpFilepath, IntPtr pResult, int length);
- [System.Runtime.InteropServices.DllImport("lyfzMD5_x64.dll")]
- public static extern int GetByteMD5(IntPtr lpBytes, int nInputlen, IntPtr pResult);
- }
- }
|