123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Runtime.Serialization.Formatters.Binary;
- using HPSocketCS.Extended;
- using System.Threading;
- using System.Drawing;
- namespace HPSocketCS
- {
- public class TcpClientEvent
- {
- public delegate HandleResult OnPrepareConnectEventHandler(TcpClient sender, uint socket);
- public delegate HandleResult OnConnectEventHandler(TcpClient sender);
- public delegate HandleResult OnSendEventHandler(TcpClient sender, byte[] bytes);
- public delegate HandleResult OnReceiveEventHandler(TcpClient sender, byte[] bytes);
- public delegate HandleResult OnCloseEventHandler(TcpClient sender, SocketOperation enOperation, int errorCode);
- }
- public class TcpClient
- {
- protected IntPtr _pClient = IntPtr.Zero;
- protected IntPtr pClient
- {
- get
- {
- return _pClient;
- }
- set
- {
- _pClient = value;
- }
- }
- protected IntPtr pListener = IntPtr.Zero;
- protected bool IsCreate = false;
- /****************************************************/
- /// <summary>
- /// 准备连接了事件
- /// </summary>
- public event TcpClientEvent.OnPrepareConnectEventHandler OnPrepareConnect;
- /// <summary>
- /// 连接事件
- /// </summary>
- public event TcpClientEvent.OnConnectEventHandler OnConnect;
- /// <summary>
- /// 数据发送事件
- /// </summary>
- public event TcpClientEvent.OnSendEventHandler OnSend;
- /// <summary>
- /// 数据到达事件
- /// </summary>
- public event TcpClientEvent.OnReceiveEventHandler OnReceive;
- /// <summary>
- /// 连接关闭事件
- /// </summary>
- public event TcpClientEvent.OnCloseEventHandler OnClose;
- public TcpClient()
- {
- CreateListener();
- }
- ~TcpClient()
- {
- Destroy();
- }
- /// <summary>
- /// 创建socket监听&服务组件
- /// </summary>
- /// <returns></returns>
- protected virtual bool CreateListener()
- {
- if (IsCreate == true || pListener != IntPtr.Zero || pClient != IntPtr.Zero)
- {
- return false;
- }
- pListener = Sdk.Create_HP_TcpClientListener();
- if (pListener == IntPtr.Zero)
- {
- return false;
- }
- pClient = Sdk.Create_HP_TcpClient(pListener);
- if (pClient == IntPtr.Zero)
- {
- return false;
- }
- IsCreate = true;
- return true;
- }
- /// <summary>
- /// 终止服务并释放资源
- /// </summary>
- public virtual void Destroy()
- {
- Stop();
- if (pClient != IntPtr.Zero)
- {
- Sdk.Destroy_HP_TcpClient(pClient);
- pClient = IntPtr.Zero;
- }
- if (pListener != IntPtr.Zero)
- {
- Sdk.Destroy_HP_TcpClientListener(pListener);
- pListener = IntPtr.Zero;
- }
- IsCreate = false;
- }
- #region 2017-02-26 修改
- string hp_address="";
- ushort hp_port=0;
- bool hp_async = false;
- string hp_bindAddress = "";
- protected bool connected;
- protected Exception exception;
- bool BeginConnected = false;
- /// <summary>
- /// 启动通讯组件并连接到服务器
- /// <param name="_timeout_milliseconds">使用者可以设置毫秒级的等待超时时间 (1000=1second)</param>
- /// </summary>
- /// <returns></returns>
- public bool Connetion(int _timeout_milliseconds=2500)
- {
- if (String.IsNullOrEmpty(hp_address))
- {
- return false;
- //throw new Exception("address is null");
- }
- else if (hp_port == 0)
- {
- return false;
- //throw new Exception("port is zero");
- }
- if (IsStarted)
- {
- return false;
- }
- connected = false;
- exception = null;
- Thread thread = new Thread(new ThreadStart(BeginConnect));
- thread.IsBackground = true; // 作为后台线程处理
- // 不会占用机器太长的时间
- thread.Start();
- // 等待如下的时间
- thread.Join(_timeout_milliseconds);
- if (connected)
- {
- // 如果成功就返回TcpClient对象
- thread.Abort();
- return BeginConnected;
- }
- if (exception != null)
- {
- // 如果失败就抛出错误
- thread.Abort();
- return BeginConnected;
- }
- else
- {
- // 同样地抛出错误
- thread.Abort();
- return BeginConnected;
- }
- }
- protected void BeginConnect()
- {
- try
- {
- BeginConnected = false;
- this.SetCallback();
- if (hp_bindAddress.Trim().Length > 1)
- {
- BeginConnected= Sdk.HP_Client_StartWithBindAddress(pClient, hp_address, hp_port, hp_async, hp_bindAddress);
- }
- else
- {
- BeginConnected= Sdk.HP_Client_Start(pClient, hp_address, hp_port, hp_async);
- }
- // 标记成功,返回调用者
- connected = true;
- }
- catch (Exception ex)
- {
- // 标记失败
- exception = ex;
- BeginConnected = false;
- }
- }
- #endregion
- /// <summary>
- /// 启动通讯组件并连接到服务器
- /// </summary>
- /// <param name="address">远程地址</param>
- /// <param name="port">远程端口</param>
- /// <param name="async">是否异步</param>
- /// <returns></returns>
- public bool Connetion(string address, ushort port, bool async = false)
- {
- if (string.IsNullOrEmpty(address) == true)
- {
- throw new Exception("address is null");
- }
- else if (port == 0)
- {
- throw new Exception("port is zero");
- }
- if (IsStarted == true)
- {
- return false;
- }
- hp_address = address;
- hp_port = port;
- hp_async = async;
-
- this.SetCallback();
- return Sdk.HP_Client_Start(pClient, address, port, async);
- }
- /// <summary>
- /// 启动通讯组件并连接到服务器
- /// </summary>
- /// <param name="address">远程地址</param>
- /// <param name="port">远程端口</param>
- /// <param name="bindAddress">本地绑定到哪个ip?,多ip下可以选择绑定到指定ip</param>
- /// <param name="async">是否异步</param>
- /// <returns></returns>
- public bool Connetion(string address, ushort port, string bindAddress, bool async = false)
- {
- if (string.IsNullOrEmpty(address) == true)
- {
- throw new Exception("address is null");
- }
- else if (port == 0)
- {
- throw new Exception("port is zero");
- }
- if (IsStarted == true)
- {
- return false;
- }
- hp_address = address;
- hp_port = port;
- hp_async = async;
- hp_bindAddress = bindAddress;
- this.SetCallback();
- return Sdk.HP_Client_StartWithBindAddress(pClient, address, port, async, bindAddress);
- }
- /// <summary>
- /// 停止通讯组件
- /// </summary>
- /// <returns></returns>
- public bool Stop()
- {
- if (IsStarted == false)
- {
- return false;
- }
- return Sdk.HP_Client_Stop(pClient);
- }
- /// <summary>
- /// 发送数据
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="bytes"></param>
- /// <param name="size"></param>
- /// <returns></returns>
- public bool Send(byte[] bytes, int size)
- {
- return Sdk.HP_Client_Send(pClient, bytes, size);
- }
- /// <summary>
- /// 发送数据
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="bufferPtr"></param>
- /// <param name="size"></param>
- /// <returns></returns>
- public bool Send(IntPtr bufferPtr, int size)
- {
- return Sdk.HP_Client_Send(pClient, bufferPtr, size);
- }
- /// <summary>
- /// 发送数据
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="bufferPtr"></param>
- /// <param name="size"></param>
- /// <returns></returns>
- public bool Send<T>(T obj)
- {
- byte[] buffer = StructureToByte<T>(obj);
- return Send(buffer, buffer.Length);
- }
- /// <summary>
- /// 序列化对象后发送数据,序列化对象所属类必须标记[Serializable]
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="bufferPtr"></param>
- /// <param name="size"></param>
- /// <returns></returns>
- public bool SendBySerializable(object obj)
- {
- byte[] buffer = ObjectToBytes(obj);
- return Send(buffer, buffer.Length);
- }
- /// <summary>
- /// 发送数据
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="bytes"></param>
- /// <param name="offset">针对bytes的偏移</param>
- /// <param name="size">发多大</param>
- /// <returns></returns>
- public bool Send(byte[] bytes, int offset, int size)
- {
- return Sdk.HP_Client_SendPart(pClient, bytes, size, offset);
- }
- /// <summary>
- /// 发送数据
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="bufferPtr"></param>
- /// <param name="offset">针对bufferPtr的偏移</param>
- /// <param name="size">发多大</param>
- /// <returns></returns>
- public bool Send(IntPtr bufferPtr, int offset, int size)
- {
- return Sdk.HP_Client_SendPart(pClient, bufferPtr, size, offset);
- }
- /// <summary>
- /// 发送多组数据
- /// 向指定连接发送多组数据
- /// TCP - 顺序发送所有数据包
- /// </summary>
- /// <param name="connId">连接 ID</param>
- /// <param name="pBuffers">发送缓冲区数组</param>
- /// <param name="iCount">发送缓冲区数目</param>
- /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
- public bool SendPackets(WSABUF[] buffers, int count)
- {
- return Sdk.HP_Client_SendPackets(pClient, buffers, count);
- }
- /// <summary>
- /// 发送多组数据
- /// 向指定连接发送多组数据
- /// TCP - 顺序发送所有数据包
- /// </summary>
- /// <param name="connId">连接 ID</param>
- /// <param name="pBuffers">发送缓冲区数组</param>
- /// <param name="iCount">发送缓冲区数目</param>
- /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
- public bool SendPackets<T>(T[] objects)
- {
- bool ret = false;
- WSABUF[] buffer = new WSABUF[objects.Length];
- IntPtr[] ptrs = new IntPtr[buffer.Length];
- try
- {
- for (int i = 0; i < objects.Length; i++)
- {
- buffer[i].Length = Marshal.SizeOf(typeof(T));
- ptrs[i] = Marshal.AllocHGlobal(buffer[i].Length);
- Marshal.StructureToPtr(objects[i], ptrs[i], true);
- buffer[i].Buffer = ptrs[i];
- }
- ret = SendPackets(buffer, buffer.Length);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- finally
- {
- for (int i = 0; i < ptrs.Length; i++)
- {
- if (ptrs[i] != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(ptrs[i]);
- }
- }
- }
- return ret;
- }
- /// <summary>
- /// 名称:发送小文件
- /// 描述:向指定连接发送 4096 KB 以下的小文件
- /// </summary>
- /// <param name="filePath">文件路径</param>
- /// <param name="head">头部附加数据</param>
- /// <param name="tail">尾部附加数据</param>
- /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
- public bool SendSmallFile(string filePath, ref WSABUF head, ref WSABUF tail)
- {
- return Sdk.HP_TcpClient_SendSmallFile(pClient, filePath, ref head, ref tail);
- }
- /// <summary>
- /// 名称:发送小文件
- /// 描述:向指定连接发送 4096 KB 以下的小文件
- /// </summary>
- /// <param name="filePath">文件路径</param>
- /// <param name="head">头部附加数据,可以为null</param>
- /// <param name="tail">尾部附加数据,可以为null</param>
- /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
- public bool SendSmallFile(string filePath, byte[] head, byte[] tail)
- {
- IntPtr pHead = IntPtr.Zero;
- IntPtr pTail = IntPtr.Zero;
- WSABUF wsaHead = new WSABUF() { Length = 0, Buffer = pHead };
- WSABUF wsatail = new WSABUF() { Length = 0, Buffer = pTail };
- if (head != null)
- {
- wsaHead.Length = head.Length;
- wsaHead.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(head, 0);
- }
- if (tail != null)
- {
- wsatail.Length = tail.Length;
- wsatail.Buffer = Marshal.UnsafeAddrOfPinnedArrayElement(tail, 0);
- }
- return SendSmallFile(filePath, ref wsaHead, ref wsatail);
- }
- /// <summary>
- /// 名称:发送小文件
- /// 描述:向指定连接发送 4096 KB 以下的小文件
- /// </summary>
- /// <param name="filePath">文件路径</param>
- /// <param name="head">头部附加数据,可以为null</param>
- /// <param name="tail">尾部附加数据,可以为null</param>
- /// <returns>TRUE.成功,FALSE.失败,可通过 SYSGetLastError() 获取 Windows 错误代码</returns>
- public bool SendSmallFile<T1, T2>(string filePath, T1 head, T2 tail)
- {
- byte[] headBuffer = null;
- if (head != null)
- {
- headBuffer = StructureToByte<T1>(head);
- }
- byte[] tailBuffer = null;
- if (tail != null)
- {
- tailBuffer = StructureToByte<T2>(tail);
- }
- return SendSmallFile(filePath, headBuffer, tailBuffer);
- }
- /// <summary>
- /// 获取错误码
- /// </summary>
- public SocketError ErrorCode
- {
- get
- {
- return Sdk.HP_Client_GetLastError(pClient);
- }
- }
- /// <summary>
- /// 获取错误信息
- /// </summary>
- public string ErrorMessage
- {
- get
- {
- IntPtr ptr = Sdk.HP_Client_GetLastErrorDesc(pClient);
- string desc = Marshal.PtrToStringUni(ptr);
- return desc;
- }
- }
- /// <summary>
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="length"></param>
- /// <returns></returns>
- public bool GetPendingDataLength(ref int length)
- {
- return Sdk.HP_Client_GetPendingDataLength(pClient, ref length);
- }
- /// <summary>
- /// 设置连接的附加数据
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="obj">如果为null,则为释放设置的数据</param>
- /// <returns></returns>
- public void SetExtra(object obj)
- {
- // 释放附加数据
- IntPtr ptr = GetExtra();
- if (ptr != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(ptr);
- ptr = IntPtr.Zero;
- }
- if (obj != null)
- {
- // 设置附加数据
- ptr = Marshal.AllocHGlobal(Marshal.SizeOf(obj));
- Marshal.StructureToPtr(obj, ptr, false);
- }
- Sdk.HP_Client_SetExtra(pClient, ptr);
- }
- /// <summary>
- /// 获取附加数据
- /// 如设置的是个结构体/类对象,可以用 Type objA = (Type)Marshal.PtrToStructure(ptr, typeof(Type)) 获取
- /// 其中Type是结构体/类名,ptr是该方法的传出值,在该方法返回为true的时候可用
- /// </summary>
- /// <param name="connId"></param>
- /// <param name="ptr"></param>
- /// <returns></returns>
- public IntPtr GetExtra()
- {
- return Sdk.HP_Client_GetExtra(pClient);
- }
- /// <summary>
- /// 获取监听socket的地址信息
- /// </summary>
- /// <param name="ip"></param>
- /// <param name="ipLength"></param>
- /// <param name="port"></param>
- /// <returns></returns>
- public bool GetListenAddress(ref string ip, ref ushort port)
- {
- int ipLength = 40;
- StringBuilder sb = new StringBuilder(ipLength);
- bool ret = Sdk.HP_Client_GetLocalAddress(pClient, sb, ref ipLength, ref port);
- if (ret == true)
- {
- ip = sb.ToString();
- }
- return ret;
- }
- /// <summary>
- /// 是否启动
- /// </summary>
- public bool IsStarted
- {
- get
- {
- if (pClient == IntPtr.Zero)
- {
- return false;
- }
- return Sdk.HP_Client_HasStarted(pClient);
- }
- }
- /// <summary>
- /// 状态
- /// </summary>
- public ServiceState State
- {
- get
- {
- return Sdk.HP_Client_GetState(pClient);
- }
- }
- /// <summary>
- /// 获取该组件对象的连接Id
- /// </summary>
- public IntPtr ConnectionId
- {
- get
- {
- return Sdk.HP_Client_GetConnectionID(pClient);
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////
- /// <summary>
- /// 读取或设置内存块缓存池大小(通常设置为 -> PUSH 模型:5 - 10;PULL 模型:10 - 20 )
- /// </summary>
- public uint FreeBufferPoolSize
- {
- get
- {
- return Sdk.HP_Client_GetFreeBufferPoolSize(pClient);
- }
- set
- {
- Sdk.HP_Client_SetFreeBufferPoolSize(pClient, value);
- }
- }
- /// <summary>
- /// 读取或设置内存块缓存池回收阀值(通常设置为内存块缓存池大小的 3 倍)
- /// </summary>
- public uint FreeBufferPoolHold
- {
- get
- {
- return Sdk.HP_Client_GetFreeBufferPoolHold(pClient);
- }
- set
- {
- Sdk.HP_Client_SetFreeBufferPoolHold(pClient, value);
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////
- /// <summary>
- /// 读取或设置通信数据缓冲区大小(根据平均通信数据包大小调整设置,通常设置为:(N * 1024) - sizeof(TBufferObj))
- /// </summary>
- public uint SocketBufferSize
- {
- get
- {
- return Sdk.HP_TcpClient_GetSocketBufferSize(pClient);
- }
- set
- {
- Sdk.HP_TcpClient_SetSocketBufferSize(pClient, value);
- }
- }
- /// <summary>
- /// 读取或设置心跳包间隔(毫秒,0 则不发送心跳包)
- /// </summary>
- public uint KeepAliveTime
- {
- get
- {
- return Sdk.HP_TcpClient_GetKeepAliveTime(pClient);
- }
- set
- {
- Sdk.HP_TcpClient_SetKeepAliveTime(pClient, value);
- }
- }
- /// <summary>
- /// 读取或设置心跳确认包检测间隔(毫秒,0 不发送心跳包,如果超过若干次 [默认:WinXP 5 次, Win7 10 次] 检测不到心跳确认包则认为已断线)
- /// </summary>
- public uint KeepAliveInterval
- {
- get
- {
- return Sdk.HP_TcpClient_GetKeepAliveInterval(pClient);
- }
- set
- {
- Sdk.HP_TcpClient_SetKeepAliveInterval(pClient, value);
- }
- }
- /// <summary>
- /// 根据错误码返回错误信息
- /// </summary>
- /// <param name="code"></param>
- /// <returns></returns>
- public string GetSocketErrorDesc(SocketError code)
- {
- IntPtr ptr = Sdk.HP_GetSocketErrorDesc(code);
- string desc = Marshal.PtrToStringUni(ptr);
- return desc;
- }
- ///////////////////////////////////////////////////////////////////////////////////////
- Sdk.OnPrepareConnect _OnPrepareConnect = null;
- Sdk.OnConnect _OnConnect = null;
- Sdk.OnReceive _OnReceive = null;
- Sdk.OnSend _OnSend = null;
- Sdk.OnClose _OnClose = null;
- /// <summary>
- /// 设置回调函数
- /// </summary>
- protected virtual void SetCallback()
- {
- // 设置 Socket 监听器回调函数
- _OnPrepareConnect = new Sdk.OnPrepareConnect(SDK_OnPrepareConnect);
- _OnConnect = new Sdk.OnConnect(SDK_OnConnect);
- _OnSend = new Sdk.OnSend(SDK_OnSend);
- _OnReceive = new Sdk.OnReceive(SDK_OnReceive);
- _OnClose = new Sdk.OnClose(SDK_OnClose);
- Sdk.HP_Set_FN_Client_OnPrepareConnect(pListener, _OnPrepareConnect);
- Sdk.HP_Set_FN_Client_OnConnect(pListener, _OnConnect);
- Sdk.HP_Set_FN_Client_OnSend(pListener, _OnSend);
- Sdk.HP_Set_FN_Client_OnReceive(pListener, _OnReceive);
- Sdk.HP_Set_FN_Client_OnClose(pListener, _OnClose);
- }
- protected HandleResult SDK_OnPrepareConnect(IntPtr pClient, uint socket)
- {
- if (OnPrepareConnect != null)
- {
- return OnPrepareConnect(this, socket);
- }
- return HandleResult.Ignore;
- }
- protected HandleResult SDK_OnConnect(IntPtr pClient)
- {
- if (OnConnect != null)
- {
- return OnConnect(this);
- }
- return HandleResult.Ignore;
- }
- protected HandleResult SDK_OnSend(IntPtr pClient, IntPtr pData, int length)
- {
- if (OnSend != null)
- {
- byte[] bytes = new byte[length];
- Marshal.Copy(pData, bytes, 0, length);
- return OnSend(this, bytes);
- }
- return HandleResult.Ignore;
- }
- protected HandleResult SDK_OnReceive(IntPtr pClient, IntPtr pData, int length)
- {
- if (OnReceive != null)
- {
- byte[] bytes = new byte[length];
- Marshal.Copy(pData, bytes, 0, length);
- return OnReceive(this, bytes);
- }
- return HandleResult.Ignore;
- }
- protected HandleResult SDK_OnClose(IntPtr pClient, SocketOperation enOperation, int errorCode)
- {
- if (OnClose != null)
- {
- return OnClose(this, enOperation, errorCode);
- }
- return HandleResult.Ignore;
- }
- ///////////////////////////////////////////////////////////////////////////
- /// <summary>
- /// 获取系统返回的错误码
- /// </summary>
- public int SYSGetLastError()
- {
- return Sdk.SYS_GetLastError();
- }
- /// <summary>
- /// 调用系统的 ::WSAGetLastError() 方法获取通信错误代码
- /// </summary>
- public int SYSWSAGetLastError()
- {
- return Sdk.SYS_WSAGetLastError();
- }
- /// <summary>
- /// 调用系统的 setsockopt()
- /// </summary>
- /// <param name="sock"></param>
- /// <param name="level"></param>
- /// <param name="name"></param>
- /// <param name="val"></param>
- /// <param name="len"></param>
- /// <returns></returns>
- ///
- public int SYS_SetSocketOption(IntPtr sock, int level, int name, IntPtr val, int len)
- {
- return Sdk.SYS_SetSocketOption(sock, level, name, val, len);
- }
- /// <summary>
- /// 调用系统的 getsockopt()
- /// </summary>
- /// <param name="sock"></param>
- /// <param name="level"></param>
- /// <param name="name"></param>
- /// <param name="val"></param>
- /// <param name="len"></param>
- /// <returns></returns>
- ///
- public int SYSGetSocketOption(IntPtr sock, int level, int name, IntPtr val, ref int len)
- {
- return Sdk.SYS_GetSocketOption(sock, level, name, val, ref len);
- }
- /// <summary>
- /// 调用系统的 ioctlsocket()
- /// </summary>
- /// <param name="sock"></param>
- /// <param name="cmd"></param>
- /// <param name="arg"></param>
- /// <returns></returns>
- ///
- public int SYSIoctlSocket(IntPtr sock, long cmd, IntPtr arg)
- {
- return Sdk.SYS_IoctlSocket(sock, cmd, arg);
- }
- /// <summary>
- /// 调用系统的 ::WSAIoctl()
- /// </summary>
- /// <param name="sock"></param>
- /// <param name="dwIoControlCode"></param>
- /// <param name="lpvInBuffer"></param>
- /// <param name="cbInBuffer"></param>
- /// <param name="lpvOutBuffer"></param>
- /// <param name="cbOutBuffer"></param>
- /// <param name="lpcbBytesReturned"></param>
- /// <returns></returns>
- public int SYS_WSAIoctl(IntPtr sock, uint dwIoControlCode, IntPtr lpvInBuffer, uint cbInBuffer,
- IntPtr lpvOutBuffer, uint cbOutBuffer, uint lpcbBytesReturned)
- {
- return Sdk.SYS_WSAIoctl(sock, dwIoControlCode, lpvInBuffer, cbInBuffer,
- lpvOutBuffer, cbOutBuffer, lpcbBytesReturned);
- }
- /// <summary>
- /// 由结构体转换为byte数组
- /// </summary>
- public 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>
- /// 由byte数组转换为结构体
- /// </summary>
- public T ByteToStructure<T>(byte[] dataBuffer)
- {
- object structure = null;
- int size = Marshal.SizeOf(typeof(T));
- IntPtr allocIntPtr = Marshal.AllocHGlobal(size);
- try
- {
- Marshal.Copy(dataBuffer, 0, allocIntPtr, size);
- structure = Marshal.PtrToStructure(allocIntPtr, typeof(T));
- }
- finally
- {
- Marshal.FreeHGlobal(allocIntPtr);
- }
- return (T)structure;
- }
- /// <summary>
- /// 对象序列化成byte[]
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public byte[] ObjectToBytes(object obj)
- {
- using (MemoryStream ms = new MemoryStream())
- {
- IFormatter formatter = new BinaryFormatter();
- formatter.Serialize(ms, obj);
- return ms.GetBuffer();
- }
- }
- /// <summary>
- /// byte[]序列化成对象
- /// </summary>
- /// <param name="Bytes"></param>
- /// <returns></returns>
- public object BytesToObject(byte[] bytes)
- {
- using (MemoryStream ms = new MemoryStream(bytes))
- {
- IFormatter formatter = new BinaryFormatter();
- return formatter.Deserialize(ms);
- }
- }
- /// <summary>
- /// byte[]转结构体
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="bytes"></param>
- /// <returns></returns>
- public T BytesToStruct<T>(byte[] bytes)
- {
- Type strcutType = typeof(T);
- int size = Marshal.SizeOf(strcutType);
- IntPtr buffer = Marshal.AllocHGlobal(size);
- try
- {
- Marshal.Copy(bytes, 0, buffer, size);
- return (T)Marshal.PtrToStructure(buffer, strcutType);
- }
- finally
- {
- Marshal.FreeHGlobal(buffer);
- }
- }
- #region 扩展方法
- CommonLibrary _CCommonLibrary = new CommonLibrary();
- /// <summary>
- /// 客户端扩展处理类
- /// </summary>
- public CommonLibrary CCommonLibrary
- {
- get { return _CCommonLibrary; }
- }
- /// <summary>
- /// 获取数据包最大长度
- /// </summary>
- /// <param name="pClient"></param>
- /// <returns></returns>
- public int GetMaxPackSize(IntPtr pClient)
- {
- return Convert.ToInt32(Sdk.HP_TcpPackClient_GetMaxPackSize(pClient));
- }
- #region 发送数据
- /// <summary>
- /// 自动拆包并发送
- /// </summary>
- /// <param name="bytes">要发送的数据</param>
- /// <param name="generateId">本次发送数据时的唯一ID</param>
- /// <returns></returns>
- public bool AutoUnpackingAndSend(byte[] bytes, Int64 generateId, DataType dType, TransferRequestCommand requestCommand, DelegateExecuteThreadStart callbackFun = null)
- {
- bool retbl = false;
- // 获取附加数据
- IntPtr clientPtr = this.GetExtra();
- ReceiveCacheBuffer cBuffer = new ReceiveCacheBuffer(generateId);
- cBuffer.CallbackFunction = callbackFun;
- this._CCommonLibrary.AddCacheBufferToList(generateId, cBuffer);
- TcpHeadInfo appendifo = CommonLibrary.GetProtocolHeader(this.ConnectionId, clientPtr, dType, requestCommand, generateId);
- int sendMaxPackSize = GetMaxPackSize(this.pClient);
- System.IO.BufferedStream sendMsstream = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, appendifo, new TcpTailInfo(), sendMaxPackSize);
- try
- {
- int bytesRead = 0;
- long totalBytes = 0;
- do
- {
- byte[] sendFileBytes = null;
- if (sendMsstream.Length - totalBytes > sendMaxPackSize)
- {
- sendFileBytes = new byte[sendMaxPackSize];
- }
- else
- {
- sendFileBytes = new byte[Convert.ToInt32(sendMsstream.Length - totalBytes)];
- }
- bytesRead = sendMsstream.Read(sendFileBytes, 0, sendFileBytes.Length);
- if (bytesRead > 0)
- {
- totalBytes += bytesRead;
- // 发送
- if (this.Send(sendFileBytes, sendFileBytes.Length))
- {
- retbl = true;
- }
- else
- {
- retbl = false;
- break;
- }
- System.Threading.Thread.Sleep(1);
- }
- Array.Clear(sendFileBytes, 0, sendFileBytes.Length);
- System.GC.Collect();
- } while (bytesRead > 0);
- }
- catch { }
- finally
- {
- sendMsstream.Close();
- sendMsstream.Dispose();
- sendMsstream = null;
- }
- /* List<byte[]> sendPakByteList = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, appendifo,new TcpTailInfo(), GetMaxPackSize(this.pClient));
- foreach (byte[] byteData in sendPakByteList)
- {
- // 发送
- if (this.Send(byteData, byteData.Length))
- {
- retbl = true;
- }
- else
- {
- retbl = false;
- break;
- }
- // System.Threading.Thread.Sleep(1);
- }
- sendPakByteList.Clear();
- sendPakByteList = null;*/
- System.GC.Collect();
- return retbl;
- }
- /// <summary>
- /// 自动拆包发送并返回结果
- /// </summary>
- /// <param name="bytes">要发送的数据</param>
- /// <param name="dType">发送的数据类型</param>
- /// <param name="requestCommand">请求命令</param>
- /// <returns></returns>
- public System.IO.MemoryStream AutoUnpackingSendAndReturnResult(byte[] bytes, DataType dType, TransferRequestCommand requestCommand, int millisecondsTimeout = 1000*90)
- {
- Int64 generateId = CommonLibrary.GenerateId();
- if (AutoUnpackingAndSend(bytes, generateId, dType, requestCommand))
- {
- return GetReceiveBytes(generateId, millisecondsTimeout);
- }
- return null;
- }
- /// <summary>
- /// 获取收到来至服务器端的数据 小于 Sdk.PacketBufferSize 数据接收
- /// </summary>
- /// <param name="generateId"></param>
- /// <param name="millisecondsTimeout"> 等待的毫秒数,或为 System.Threading.Timeout.Infinite (-1),表示无限期等待。</param>
- /// <returns></returns>
- System.IO.MemoryStream GetReceiveBytes(Int64 generateId, int millisecondsTimeout = 1000*90)
- {
- System.IO.MemoryStream retBytes = new MemoryStream();
- try
- {
- ReceiveCacheBuffer recBuffer = this.CCommonLibrary.GetReceiveCacheBuffer(generateId);
- if (recBuffer != null)
- {
- recBuffer.MEvent.WaitOne(millisecondsTimeout);
- recBuffer.DataBuffer.WriteTo(retBytes);
- }
-
- }
- catch { }
- finally
- {
- _CCommonLibrary.RemoveServerToClientByteList(generateId);
- }
- if (retBytes.Length > 0)
- {
- retBytes.Position = 0;
- return retBytes;
- }
- else {
- retBytes.Close();
- retBytes.Dispose();
- retBytes = null;
- return null;
- }
- }
-
- /// <summary>
- /// 回调函数
- /// </summary>
- /// <param name="b"></param>
- void WaitThreadFunc(object b)
- {
- ParameterObject pobj = (ParameterObject)b;
- Int64 generateId = CommonLibrary.GenerateId();
- try
- {
- if (AutoUnpackingAndSend(pobj.SendBytes, generateId, pobj.DType,pobj.RequestCommand, pobj.CallbackFun))
- {
- ReceiveCacheBuffer recBuffer = this.CCommonLibrary.GetReceiveCacheBuffer(generateId);
- if (recBuffer != null)
- {
- recBuffer.MEvent.WaitOne(1000 * 90);
- }
- }
- }
- catch { }
- finally
- {
- _CCommonLibrary.RemoveServerToClientByteList(generateId);
- }
- }
- /// <summary>
- /// 自动拆包发送并回调指定函数
- /// </summary>
- /// <param name="bytes"></param>
- /// <param name="dType"></param>
- /// <param name="requestCommand">请求命令</param>
- /// <param name="dethStart"></param>
- public void AutoUnpackingSendAndWaitCallback(byte[] bytes, DataType dType, TransferRequestCommand requestCommand, DelegateExecuteThreadStart callbackFun)
- {
- ParameterObject pobj = new ParameterObject();
- pobj.CallbackFun = callbackFun;
- pobj.DType = dType;
- pobj.RequestCommand = requestCommand;
- pobj.SendBytes = bytes;
- ThreadPool.QueueUserWorkItem(new WaitCallback(WaitThreadFunc), pobj);
- }
- #endregion
- #region 上传下载文件
- #region 上传
- /// <summary>
- /// 上传图片
- /// </summary>
- /// <param name="img"></param>
- /// <param name="toServerFileName"></param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public bool UploadImage(Bitmap bmp, string toServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- bool retbl = false;
- MemoryStream memoryMS = new MemoryStream();
- try
- {
- bmp.Save(memoryMS, bmp.RawFormat);
- byte[] sendFileBytes = memoryMS.ToArray();
- if (sendFileBytes.Length > 0)
- {
- retbl = UploadFiles(sendFileBytes, sendFileBytes.Length, toServerFileName, backgroundWorker);
- }
- }
- finally
- {
- memoryMS.Close();
- memoryMS.Dispose();
- memoryMS = null;
- }
- return retbl;
- }
- /// <summary>
- /// 上传图片
- /// </summary>
- /// <param name="img"></param>
- /// <param name="toServerFileName"></param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public bool UploadImage(Image img, string toServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- bool retbl = false;
- MemoryStream memoryMS = new MemoryStream();
- try
- {
- img.Save(memoryMS, img.RawFormat);
- memoryMS.Position = 0;
- byte[] sendFileBytes = new byte[memoryMS.Length];
- memoryMS.Read(sendFileBytes, 0, sendFileBytes.Length);
- if (sendFileBytes.Length > 0)
- {
- retbl = UploadFiles(sendFileBytes, sendFileBytes.Length, toServerFileName, backgroundWorker);
- }
- }
- finally {
- memoryMS.Close();
- memoryMS.Dispose();
- memoryMS = null;
- }
- return retbl;
- }
- /// <summary>
- /// 上传内存流
- /// </summary>
- /// <param name="memoryMS"></param>
- /// <param name="toServerFileName"></param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public bool UploadMemoryStream(MemoryStream memoryMS, string toServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- bool retbl = false;
- try
- {
- if (memoryMS != null)
- {
- memoryMS.Position = 0;
- byte[] sendFileBytes = new byte[memoryMS.Length];//memoryMS.GetBuffer();
- memoryMS.Read(sendFileBytes, 0, sendFileBytes.Length);
- if (sendFileBytes.Length > 0)
- {
- retbl = UploadFiles(sendFileBytes, sendFileBytes.Length, toServerFileName, backgroundWorker);
- }
- }
- }
- finally
- {
- memoryMS.Close();
- memoryMS.Dispose();
- memoryMS = null;
- }
- return retbl;
- }
- /// <summary>
- /// 上传文件
- /// </summary>
- /// <param name="fileName"></param>
- /// <param name="toServerFileName"></param>
- /// <returns></returns>
- public bool UploadFiles(string fileName, string toServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- bool retbl = false;
- if (System.IO.File.Exists(fileName))
- {
- FileInfo fi = new FileInfo(fileName);
- // 创建文件流
- FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
- System.IO.BufferedStream buffStream = new BufferedStream(fs, Sdk.PacketBufferSize*2);
- try
- {
- int Subcontract = Sdk.PacketBufferSize;//分包大小
- int bytesRead = 0;
- long totalBytes = 0;
- do
- {
- byte[] sendFileBytes = null;
- if (fi.Length - totalBytes > Subcontract)
- {
- sendFileBytes = new byte[Subcontract];
- }
- else
- {
- sendFileBytes = new byte[fi.Length - totalBytes];
- }
- bytesRead = buffStream.Read(sendFileBytes, 0, sendFileBytes.Length);
-
- if (bytesRead > 0)
- {
- bool IsSendComplete = false;
- if (totalBytes + bytesRead >= fi.Length)
- {
- IsSendComplete = true;
- }
- if (totalBytes <= 0)
- {
- retbl = UploadFiles(sendFileBytes, fi.Length, toServerFileName, backgroundWorker, IsSendComplete: IsSendComplete);
- }
- else
- {
- retbl = UploadFiles(sendFileBytes, fi.Length, toServerFileName, backgroundWorker, FileMode.Append, totalBytes, IsSendComplete);
- }
- totalBytes += bytesRead;
- }
- Array.Clear(sendFileBytes, 0, sendFileBytes.Length);
- System.GC.Collect();
- } while (bytesRead > 0);
-
- }
- catch
- {
- }
- finally {
- buffStream.Flush();
- buffStream.Close();
- buffStream.Dispose();
- buffStream = null;
- fs.Close();
- fs.Dispose();
- fs = null;
- }
- }
- return retbl;
- }
-
- /// <summary>
- /// 上传文件字节数组
- /// </summary>
- /// <param name="sendFileBytes">要发送的字节数组</param>
- /// <param name="sendTotalSize">要发送的文件总大小</param>
- /// <param name="toServerFileName">要保存的文件名或路径</param>
- /// <param name="backgroundWorker"></param>
- /// <param name="mode">文件打开方式</param>
- /// <param name="hasBeenSentSize">已发送大小</param>
- /// <returns></returns>
- public bool UploadFiles(byte[] sendFileBytes, long sendTotalSize, string toServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null, FileMode mode = FileMode.Create, long hasBeenSentSize = 0, bool IsSendComplete=true)
- {
- bool retbl = false;
- /* if (sendFileBytes.Length > (Sdk.PacketBufferSize))
- {
- throw new Exception("上传文件大小不能超过" + (Sdk.PacketBufferSize / 1024 / 1024) + "MB。");
- }
- else */
- if (sendFileBytes.Length == 0)
- {
- throw new Exception("上传文件大小不能为0。");
- }
- //总计数器
- long sumCount = sendTotalSize;
- //当前计数器
- long currentCount = hasBeenSentSize;
- Int64 generateId = CommonLibrary.GenerateId();
- // 获取附加数据
- IntPtr clientPtr = this.GetExtra();
- // 头附加数据
- TcpHeadInfo headinfo = CommonLibrary.GetProtocolHeader(this.ConnectionId, clientPtr, DataType.File, TransferRequestCommand.FileTransfer, generateId, true);
- // 附加尾数据
- TcpTailInfo tailinfo = new TcpTailInfo();
- tailinfo.FileName = toServerFileName;
- tailinfo.FileSize =sendTotalSize;
- tailinfo.RequestType = (int)FileRequestType.Upload;
- tailinfo.FileMode = (int)mode;
- tailinfo.IsSendComplete = IsSendComplete;
- int sendMaxPackSize = GetMaxPackSize(this.pClient);
- System.IO.BufferedStream sendMsstream = CommonLibrary.AutoUnpackingAndAddPkgHeader(sendFileBytes, headinfo, tailinfo, sendMaxPackSize);
- try
- {
- int bytesRead = 0;
- long totalBytes = 0;
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount, "正在上传,请稍等...", backgroundWorker);
- do
- {
- byte[] sendDataBytes = null;
- if (sendMsstream.Length - totalBytes > sendMaxPackSize)
- {
- sendDataBytes = new byte[sendMaxPackSize];
- }
- else
- {
- sendDataBytes = new byte[Convert.ToInt32(sendMsstream.Length - totalBytes)];
- }
- bytesRead = sendMsstream.Read(sendDataBytes, 0, sendDataBytes.Length);
- if (bytesRead > 0)
- {
- totalBytes += bytesRead;
- currentCount += sendDataBytes.Length;
- // 发送
- if (this.Send(sendDataBytes, sendDataBytes.Length))
- {
- retbl = true;
- }
- else
- {
- retbl = false;
- break;
- }
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount, "正在上传,请稍等...", backgroundWorker);
- System.Threading.Thread.Sleep(1);
- }
- Array.Clear(sendDataBytes, 0, sendDataBytes.Length);
- System.GC.Collect();
- } while (bytesRead > 0);
- if (IsSendComplete)
- {
- currentCount = sumCount;
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount, "上传完成", backgroundWorker);
- }
- }
- catch { }
- finally
- {
- sendMsstream.Close();
- sendMsstream.Dispose();
- sendMsstream = null;
- }
- /* List<byte[]> sendPakByteList = CommonLibrary.AutoUnpackingAndAddPkgHeader(sendFileBytes, headinfo, tailinfo, GetMaxPackSize(this.pClient));
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount, "正在上传,请稍等...", backgroundWorker);
- foreach (byte[] byteData in sendPakByteList)
- {
- currentCount += byteData.Length;
- // 发送
- if (this.Send(byteData, byteData.Length))
- {
- retbl = true;
- }
- else
- {
- retbl = false;
- break;
- }
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount, "正在上传,请稍等...", backgroundWorker);
- System.Threading.Thread.Sleep(3);
- }
- if (currentCount >= sumCount)
- {
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount, "上传完成", backgroundWorker);
- }
- sendPakByteList.Clear();
- sendPakByteList = null;*/
- System.GC.Collect();
- return retbl;
- }
- #endregion
- #region 下载
- /// <summary>
- /// 接收下载的文件数据包处理
- /// </summary>
- /// <param name="header"></param>
- /// <param name="tail"></param>
- /// <param name="recBuffer"></param>
- /// <param name="recbytes"></param>
- public bool ReceiveDownloadFile(TcpHeadInfo header, TcpTailInfo tail, ReceiveCacheBuffer recBuffer, byte[] recbytes)
- {
- try
- {
- if (recBuffer != null)
- {
- lock (recBuffer)
- {
- if (recBuffer.SaveToFileName.Trim().Length <= 0)
- {
- return recBuffer.ReceiveComplete(recbytes,tail.IsSendComplete);
- }
- else
- {
- string saveFilePath = recBuffer.SaveToFileName;
- string saveDirPath = System.IO.Path.GetDirectoryName(saveFilePath);
- if (!System.IO.Directory.Exists(saveDirPath))
- {
- try
- {
- System.IO.Directory.CreateDirectory(saveDirPath);
- }
- catch { }
- }
- FileMode fMode = (FileMode)tail.FileMode;
- FileStream fs = new FileStream(saveFilePath, fMode, FileAccess.Write);
- System.IO.BufferedStream buffStream = new BufferedStream(fs,Sdk.PacketBufferSize*2);
- try
- {
- buffStream.Write(recbytes, 0, recbytes.Length);
- buffStream.Flush();
- // fs.Write(recbytes, 0, recbytes.Length);
- }
- finally
- {
- buffStream.Close();
- buffStream.Dispose();
- fs.Close();
- fs.Dispose();
- }
- if (tail.IsSendComplete || recBuffer.Length >= tail.FileSize)
- {
- recBuffer.IsReceiveComplete = true;
- recBuffer.MEvent.Set();
- }
- return true;
- }
- }
- }
- else {
- return false;
- }
- }
- catch {
- return false;
- }
- }
- /// <summary>
- /// 发送下载请求
- /// </summary>
- /// <param name="generateId"></param>
- /// <param name="comeFromServerFileName">要下载的文件名/路径</param>
- /// <param name="saveToFileName">下载文件要保存的路径</param>
- /// <param name="backgroundWorker">进程报告对象</param>
- /// <returns></returns>
- bool SenDownloadQequest(Int64 generateId, string comeFromServerFileName, string saveToFileName="", System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- bool retbl = false;
- // 获取附加数据
- IntPtr clientPtr = this.GetExtra();
- // 头附加数据
- TcpHeadInfo headinfo = CommonLibrary.GetProtocolHeader(this.ConnectionId, clientPtr, DataType.File, TransferRequestCommand.FileTransfer, generateId, true);
- // 附加尾数据
- TcpTailInfo tailinfo = new TcpTailInfo();
- tailinfo.FileName = comeFromServerFileName;
- tailinfo.FileSize = 0;
- tailinfo.RequestType = (int)FileRequestType.Download;
- tailinfo.FileMode = (int)FileMode.Create;
- tailinfo.IsSendComplete = false;
- ReceiveCacheBuffer cBuffer = new ReceiveCacheBuffer(generateId);
- cBuffer.SaveToFileName=saveToFileName;
- cBuffer.BackgroundWorker = backgroundWorker;
- cBuffer.CallbackFunction = null;
- this._CCommonLibrary.AddCacheBufferToList(generateId, cBuffer);
- byte[] bytes = Encoding.UTF8.GetBytes("Download File");
- int sendMaxPackSize = GetMaxPackSize(this.pClient);
- // List<byte[]> sendPakByteList = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, appendifo,new TcpTailInfo(), GetMaxPackSize(this.pServer));
- System.IO.BufferedStream sendMsstream = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, headinfo, tailinfo, sendMaxPackSize);
- try
- {
- int bytesRead = 0;
- long totalBytes = 0;
- do
- {
- byte[] sendFileBytes = null;
- if (sendMsstream.Length - totalBytes > sendMaxPackSize)
- {
- sendFileBytes = new byte[sendMaxPackSize];
- }
- else
- {
- sendFileBytes = new byte[Convert.ToInt32(sendMsstream.Length - totalBytes)];
- }
- bytesRead = sendMsstream.Read(sendFileBytes, 0, sendFileBytes.Length);
- if (bytesRead > 0)
- {
- totalBytes += bytesRead;
- // 发送
- if (this.Send(sendFileBytes, sendFileBytes.Length))
- {
- retbl = true;
- }
- else
- {
- retbl = false;
- break;
- }
- System.Threading.Thread.Sleep(1);
- }
- Array.Clear(sendFileBytes, 0, sendFileBytes.Length);
- System.GC.Collect();
- } while (bytesRead > 0);
- }
- catch { }
- finally
- {
- sendMsstream.Close();
- sendMsstream.Dispose();
- sendMsstream = null;
- }
- /* List<byte[]> sendPakByteList = CommonLibrary.AutoUnpackingAndAddPkgHeader(bytes, headinfo, tailinfo, GetMaxPackSize(this.pClient));
- foreach (byte[] byteData in sendPakByteList)
- {
- // 发送
- if (this.Send(byteData, byteData.Length))
- {
- retbl = true;
- }
- else
- {
- retbl = false;
- break;
- }
- System.Threading.Thread.Sleep(1);
- }
- sendPakByteList.Clear();
- sendPakByteList = null;*/
- System.GC.Collect();
- return retbl;
-
- }
- /// <summary>
- /// 下载到内存流
- /// </summary>
- /// <param name="comeFromServerFileName"></param>
- /// <returns></returns>
- public MemoryStream DownloadMemoryStream(string comeFromServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- Int64 generateId = CommonLibrary.GenerateId();
- if (SenDownloadQequest(generateId, comeFromServerFileName, "", backgroundWorker))
- {
- return GetReceiveBytes(generateId, System.Threading.Timeout.Infinite);
- }
- return null;
- }
- /// <summary>
- /// 下载文件并保存
- /// </summary>
- /// <param name="comeFromServerFileName">要下载的文件名/或路径</param>
- /// <param name="saveToFileName">下载后的保存路径</param>
- /// <param name="backgroundWorker"></param>
- public bool DownloadFiles(string comeFromServerFileName,string saveToFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- Int64 generateId = CommonLibrary.GenerateId();
- bool ret = false;
- if (SenDownloadQequest(generateId, comeFromServerFileName, saveToFileName, backgroundWorker))
- {
- try
- {
- ReceiveCacheBuffer recBuffer = this.CCommonLibrary.GetReceiveCacheBuffer(generateId);
- if (recBuffer != null)
- {
- recBuffer.MEvent.WaitOne(System.Threading.Timeout.Infinite);
- ret= recBuffer.IsReceiveComplete;
- }
- }
- catch { }
- finally
- {
- _CCommonLibrary.RemoveServerToClientByteList(generateId);
- }
- }
- return ret;
- }
- /// <summary>
- /// 下载图片
- /// </summary>
- /// <param name="img"></param>
- /// <param name="toServerFileName"></param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public Bitmap DownloadBitmap(string comeFromServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- Bitmap bmp=null;
- MemoryStream memoryMS = DownloadMemoryStream(comeFromServerFileName, backgroundWorker);
- try
- {
- if (memoryMS != null && memoryMS.Length>0)
- bmp = new Bitmap(memoryMS);
- }
- finally
- {
- if (memoryMS != null)
- {
- memoryMS.Close();
- memoryMS.Dispose();
- memoryMS = null;
- }
- }
- return bmp;
- }
- /// <summary>
- /// 下载图片
- /// </summary>
- /// <param name="img"></param>
- /// <param name="toServerFileName"></param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public Image DownloadImage(string comeFromServerFileName, System.ComponentModel.BackgroundWorker backgroundWorker = null)
- {
- return DownloadBitmap(comeFromServerFileName, backgroundWorker);
- }
-
-
- #endregion
- #endregion
- #endregion
- }
- /// <summary>
- /// 参数对象
- /// </summary>
- public class ParameterObject {
- public ParameterObject() {
-
- }
- DelegateExecuteThreadStart _callbackFun;
- public DelegateExecuteThreadStart CallbackFun
- {
- get { return _callbackFun; }
- set { _callbackFun = value; }
- }
- System.ComponentModel.BackgroundWorker backgroundWorker;
- public System.ComponentModel.BackgroundWorker BackgroundWorker
- {
- get { return backgroundWorker; }
- set { backgroundWorker = value; }
- }
- byte[] _sendBytes;
- public byte[] SendBytes
- {
- get { return _sendBytes; }
- set { _sendBytes = value; }
- }
- string fileName;
- public string FileName
- {
- get { return fileName; }
- set { fileName = value; }
- }
- DataType dType = DataType.Text;
- public DataType DType
- {
- get { return dType; }
- set { dType = value; }
- }
- TransferRequestCommand requestCommand = TransferRequestCommand.Message;
- /// <summary>
- /// 请求命令
- /// </summary>
- public TransferRequestCommand RequestCommand
- {
- get { return requestCommand; }
- set { requestCommand = value; }
- }
- }
- }
|