123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.IO;
- using System.ComponentModel;
- using HPSocketCS.Extended;
- using System.Runtime.InteropServices;
- namespace HPNetwork.TCPNetworkClient
- {
- /// <summary>
- /// TCP网络通信客户端
- /// </summary>
- public class TCP_NetworkClient
- {
- public TCP_NetworkClient() {
-
- }
- #region 网络客户端程序处理代码
- TCP_NetworkClient tFileClient=null;
- /// <summary>
- /// 文件传送通道
- /// </summary>
- public TCP_NetworkClient TFileClient
- {
- get {
- if (this.tFileClient == null)
- {
- this.tFileClient = new TCP_NetworkClient();
- }
- return this.tFileClient;
- }
- }
- private AppState appState = AppState.Stoped;
- /// <summary>
- /// 当前网络状态
- /// </summary>
- public AppState AppState
- {
- get { return appState; }
- set { appState = value; }
- }
- // private delegate void ConnectUpdateUiDelegate();
- // private delegate void SetAppStateDelegate(AppState state);
- HPSocketCS.TcpPackClient client = new HPSocketCS.TcpPackClient();
- /// <summary>
- /// 客户端连接
- /// </summary>
- public HPSocketCS.TcpPackClient Client
- {
- get { return client; }
- }
- /// <summary>
- /// 连接服务器
- /// </summary>
- /// <param name="ip">ip</param>
- /// <param name="port">端口</param>
- /// <param name="isAsyncConn">是否异步连接</param>
- /// <returns></returns>
- public bool ConnectionServer(string hostOrIP="", ushort port=0, bool isAsyncConn = false)
- {
- try
- {
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- return true;
- }
- if (!this.isInitializesNetwork)
- {
- this.InitializesNetwork();
- }
- bool cAsyncConn = isAsyncConn;
- // 写在这个位置是上面可能会异常
- SetAppState(AppState.Starting);
- // AddMsg(string.Format("$Client Starting ... -> ({0}:{1})", ip, port));
- SystemFileLogs.WriteLogs(string.Format("客户端开始连接... -> ({0}:{1})", hostOrIP, port));
- if (client.Connetion(hostOrIP, port, cAsyncConn))
- {
- if (cAsyncConn == false)
- {
- SetAppState(AppState.Started);
- }
- // AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
- SystemFileLogs.WriteLogs(string.Format("客户端连接OK -> ({0}:{1})", hostOrIP, port));
- return true;
- }
- else
- {
- SetAppState(AppState.Stoped);
- throw new Exception(string.Format("客户端连接出错 -> {0}({1})", client.ErrorMessage, client.ErrorCode));
- }
- }
- catch (Exception ex)
- {
- SystemFileLogs.WriteLogs(string.Format("客户端连接失败-> ({0})", ex.Message));
- }
- return false;
- }
- /// <summary>
- /// 关闭客户端连接
- /// </summary>
- /// <returns></returns>
- public bool CloseConnected()
- {
- // 停止服务
- SystemFileLogs.WriteLogs(string.Format("准备关闭客户端连接"));
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- if (client.Stop())
- {
- SetAppState(AppState.Stoped);
- if (this.tFileClient != null && this.tFileClient.AppState == HPSocketCS.Extended.AppState.Started)
- {
- this.tFileClient.CloseConnected();
- }
- return true;
- }
- else
- {
- // AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
- SystemFileLogs.WriteLogs(string.Format("关闭客户端连接失败-> {0}({1})", client.ErrorMessage, client.ErrorCode));
- }
- }
- else {
- return true;
- }
- return false;
- }
- bool isInitializesNetwork = false;
- /// <summary>
- /// 网络服务是否已初始化
- /// </summary>
- public bool IsInitializesNetwork
- {
- get { return isInitializesNetwork; }
- set { isInitializesNetwork = value; }
- }
- /// <summary>
- /// 初始化网络
- /// </summary>
- void InitializesNetwork()
- {
- try
- {
-
- // 设置client事件
- client.OnPrepareConnect += new HPSocketCS.TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
- client.OnConnect += new HPSocketCS.TcpClientEvent.OnConnectEventHandler(OnConnect);
- client.OnSend += new HPSocketCS.TcpClientEvent.OnSendEventHandler(OnSend);
- client.OnReceive += new HPSocketCS.TcpClientEvent.OnReceiveEventHandler(OnReceive);
- client.OnClose += new HPSocketCS.TcpClientEvent.OnCloseEventHandler(OnClose);
- // 设置包头标识,与对端设置保证一致性
- client.PackHeaderFlag = 0x1ff;
- // 设置最大封包大小
- client.MaxPackSize = 0x2000 * 32;
- client.SocketBufferSize = 512 * 1024;//client.MaxPackSize;
- SystemFileLogs.WriteLogs("客户初始化网络成功");
- SetAppState(AppState.Stoped);
- this.isInitializesNetwork = true;
- }
- catch (Exception ex)
- {
- SetAppState(AppState.Error);
- // AddMsg(ex.Message);
- SystemFileLogs.WriteLogs("客户初始化网络时出错:" + ex.Message);
- }
- }
- HPSocketCS.HandleResult OnPrepareConnect(HPSocketCS.TcpClient sender, uint socket)
- {
- return HPSocketCS.HandleResult.Ok;
- }
- HPSocketCS.HandleResult OnConnect(HPSocketCS.TcpClient sender)
- {
- // 已连接 到达一次
- // 设置附加数据
- string ip = "";
- ushort port = 0;
- if (sender.GetListenAddress(ref ip, ref port))
- {
- HPSocketCS.Extended.ClientInfo ci = new HPSocketCS.Extended.ClientInfo();
- ci.ConnId = sender.ConnectionId;
- ci.IpAddress = ip;
- ci.Port = port;
- sender.SetExtra(ci);
- }
- // 如果是异步联接,更新界面状态
- // this.Invoke(new ConnectUpdateUiDelegate(ConnectUpdateUi));
- // AddMsg(string.Format(" > [{0},OnConnect]", sender.ConnectionId));
- SystemFileLogs.WriteLogs("已连接:" + ip + ":" + port.ToString());
- return HPSocketCS.HandleResult.Ok;
- }
- HPSocketCS.HandleResult OnSend(HPSocketCS.TcpClient sender, byte[] bytes)
- {
-
- // 客户端发数据了
- //AddMsg(string.Format(" > [{0},OnSend] ->数据发送成功 ({1} bytes)", sender.ConnectionId, bytes.Length));
-
- return HPSocketCS.HandleResult.Ok;
- }
- HPSocketCS.HandleResult OnReceive(HPSocketCS.TcpClient sender, byte[] bytes)
- {
- // 数据到达了
- try
- {
- //收到的数据
- byte[] receiveBytes = new byte[0];
- TcpHeadInfo header = sender.BytesToStruct<TcpHeadInfo>(bytes);
- try
- {
- DataType dType = (DataType)header.MsgDataType;
- int headSize = Marshal.SizeOf(header);
- TcpTailInfo tail = new TcpTailInfo();
-
- if (header.IsTail)
- {
- //有附加尾数据时
- int tailSize = Marshal.SizeOf(tail);
- byte[] tailBytes = new byte[tailSize];
- Array.ConstrainedCopy(bytes, bytes.Length - tailSize, tailBytes, 0, tailBytes.Length);
- tail = sender.BytesToStruct<TcpTailInfo>(tailBytes);
- receiveBytes = new byte[bytes.Length - headSize - tailSize];
- Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
- tailBytes = null;
- }
- else
- {
- // 因为没有附加尾数据,所以大小可以用length - objSize
- receiveBytes = new byte[bytes.Length - headSize];
- Array.ConstrainedCopy(bytes, headSize, receiveBytes, 0, receiveBytes.Length);
- }
-
- ReceiveCacheBuffer recBuffer = sender.CCommonLibrary.GetReceiveCacheBuffer(header.TransportID);
- if (recBuffer != null)
- {
- lock (recBuffer)
- {
- recBuffer.Length += receiveBytes.Length;
- if (recBuffer.BackgroundWorker != null)
- {
- //总计数器
- long sumCount = header.IntactSize;
- if (dType == DataType.File)
- {
- sumCount = tail.FileSize;
- }
- //当前计数器
- long currentCount = recBuffer.Length;
- if (header.TransportEnd && tail.IsSendComplete)
- {
- currentCount = Convert.ToInt64(sumCount);
- }
- CommonLibrary.SetBackgroundWorker(sumCount, currentCount,"正在接收数据,请稍等...", recBuffer.BackgroundWorker);
- }
- }
- }
- //接收到的客户端发送来的数据
- byte[] recbytes = null;
- try
- {
- if (header.TransportStart && header.TransportEnd)
- {
- recbytes = receiveBytes;
- receiveBytes = null;
- }
- else
- {
- ReceiveData rData = sender.CCommonLibrary.GetReceiveData(header);
- if (rData == null)
- {
- rData = new ReceiveData();
- sender.CCommonLibrary.AddReceiveData(rData);
- }
- rData.ReceiveRemoteClientInfo = header;
- rData.ReceiveDataMstream.Write(receiveBytes, 0, receiveBytes.Length);
- if (header.TransportEnd)
- {
- recbytes = rData.ReceiveDataMstream.ToArray();
- sender.CCommonLibrary.RemoveReceiveDataData(rData);
- }
- }
- if (recbytes != null)
- {
- recbytes = HPSocketCS.Extended.DataSetSerializerDeserialize.DataDecompressRetBytes(recbytes);
- if (!header.IsTail && header.TransportEnd)
- {
- tail.IsSendComplete = true;
- }
- switch (dType)
- {
- case DataType.Text:
- if (recBuffer != null)
- {
- if (!recBuffer.ReceiveComplete(recbytes,tail.IsSendComplete))
- {
- return HPSocketCS.HandleResult.Error;
- }
- }
- break;
- case DataType.File:
- if (!sender.ReceiveDownloadFile(header, tail, recBuffer, recbytes))
- {
- return HPSocketCS.HandleResult.Error;
- }
- break;
- case DataType.Serialization:
- case DataType.SQLHelper:
- if (recBuffer != null)
- {
- if (!recBuffer.ReceiveComplete(recbytes, tail.IsSendComplete))
- {
- return HPSocketCS.HandleResult.Error;
- }
- }
- // break;
-
- break;
- case DataType.List:
- break;
- case DataType.Array:
- break;
- case DataType.None:
- break;
-
- }
- }
- }
- finally
- {
- recbytes = null;
- }
- return HPSocketCS.HandleResult.Ok;
- }
- catch
- {
- sender.CCommonLibrary.RemoveServerToClientByteList(header.TransportID);
- return HPSocketCS.HandleResult.Ignore;
- }
- }
- catch (Exception ex)
- {
- SystemFileLogs.WriteLogs("接收数据时出错:" + ex.Message);
- return HPSocketCS.HandleResult.Error;
- }
- finally
- {
- System.GC.Collect();
- }
- }
- HPSocketCS.HandleResult OnClose(HPSocketCS.TcpClient sender, HPSocketCS.SocketOperation enOperation, int errorCode)
- {
- try
- {
- try
- {
- sender.CCommonLibrary.ClearAllInvalidResource();
- }
- catch { }
- try
- {
- sender.CCommonLibrary.ClearAllServerToClientByteList();
- }
- catch { }
- SetAppState(AppState.Stoped);
- if (errorCode == 0)
- {
- // 连接关闭了
- // AddMsg(string.Format(" > [{0},OnClose]", sender.ConnectionId));
- SystemFileLogs.WriteLogs("连接关闭了");
- }
- else if (enOperation == HPSocketCS.SocketOperation.Close)
- {
- SystemFileLogs.WriteLogs(string.Format(" 服务器已关闭连接> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
- }
- else
- {
- // 出错了
- // AddMsg(string.Format(" > [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
- SystemFileLogs.WriteLogs(string.Format(" 连接出错了> [{0},OnError] -> OP:{1},CODE:{2}", sender.ConnectionId, enOperation, errorCode));
- }
- // 通知界面,只处理了连接错误,也没进行是不是连接错误的判断,所以有错误就会设置界面
- // 生产环境请自己控制
- // this.Invoke(new SetAppStateDelegate(SetAppState), AppState.Stoped);
- }
- catch { }
- return HPSocketCS.HandleResult.Ok;
- }
- /// <summary>
- /// 设置程序状态
- /// </summary>
- /// <param name="state"></param>
- void SetAppState(AppState state)
- {
- appState = state;
- }
-
-
-
- /// <summary>
- /// 上传头像
- /// </summary>
- /// <param name="fileFullName">要上传的头像路径</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string UploadAvatarToServer(string fileFullName, BackgroundWorker backgroundWorker = null)
- {
- return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, fileFullName, System.IO.Path.GetFileName(fileFullName), backgroundWorker);
- }
- /// <summary>
- /// 上传文件
- /// </summary>
- /// <param name="fileFullName">要上传的文件路径</param>
- /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string UploadFileToServer(string fileFullName, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
- {
- return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, fileFullName, toServerFileFullName, backgroundWorker);
- }
- /// <summary>
- /// 上传图片
- /// </summary>
- /// <param name="img">要上传的图片</param>
- /// <param name="imgFormat">上传的图片格式</param>
- /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="isDisposeImg">上传后是否释放图片资源</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string UploadFileToServer(System.Drawing.Image img, System.Drawing.Imaging.ImageFormat imgFormat, string toServerFileFullName, BackgroundWorker backgroundWorker = null, bool isDisposeImg = true)
- {
- MemoryStream memoryMS = new MemoryStream();
- img.Save(memoryMS, imgFormat);
- if (isDisposeImg)
- {
- img.Dispose();
- }
- return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
- }
- /// <summary>
- /// 上传内存流
- /// </summary>
- /// <param name="memoryMS">要上传的内存流</param>
- /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定为 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="isDisposeImg">上传后是否释放图片资源</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string UploadFileToServer(MemoryStream memoryMS, string toServerFileFullName, BackgroundWorker backgroundWorker = null)
- {
- return SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand.UploadFile, "", toServerFileFullName, backgroundWorker, memoryMS: memoryMS);
- }
- /// <summary>
- /// 获取指定服务器端文件的信息
- /// </summary>
- /// <param name="sFileName">为你向服务器请求的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
- /// <returns></returns>
- public ServerFileInfo GetServerFileInfo(string sFileName)
- {
- ServerFileInfo sFileInfo = new ServerFileInfo();
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- try
- {
-
- // sFileInfo = new ServerFileInfo(sendFileProtocol.Content);
- }
- catch { sFileInfo.GetMsg = "连接已断开,请检查网络环境是否正常..."; }
- }
- return sFileInfo;
- }
- /// <summary>
- /// 下载头像
- /// </summary>
- /// <param name="backgroundWorker"></param>
- /// <param name="saveFileFullName">头像下载后保存的位置</param>
- /// <param name="fileName">头像图片名(带扩展名)</param>
- /// <returns></returns>
- public string DownloadAvatar(string saveFileFullName, string fileName, BackgroundWorker backgroundWorker = null)
- {
- return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, fileName, fileName, backgroundWorker);
- }
- /// <summary>
- /// 下载头像
- /// </summary>
- /// <param name="backgroundWorker"></param>
- /// <param name="memoryMS">保存到指定的内存流中</param>
- /// <param name="fileName">头像图片名(带扩展名)</param>
- /// <returns></returns>
- public string DownloadAvatar(MemoryStream memoryMS, string fileName, BackgroundWorker backgroundWorker = null)
- {
- return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
- }
- /// <summary>
- /// 下载头像
- /// </summary>
- /// <param name="resultBitmap">返回下载的图片</param>
- /// <param name="fileName">头像图片名(带扩展名)</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string DownloadAvatar(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
- {
- try
- {
- MemoryStream ImageMS = new MemoryStream();
- string retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, "", fileName, backgroundWorker);
- try
- {
- resultBitmap = new System.Drawing.Bitmap(ImageMS);
- }
- catch
- {
- retMsg = "下载失败,头像生成时失败";
- }
- ImageMS.Close();
- ImageMS.Dispose();
- return retMsg;
- }
- catch (Exception ex)
- {
- return "下载失败:" + ex.ToString();
- }
- }
- /// <summary>
- /// 下载文件
- /// </summary>
- /// <param name="saveFileFullName">下载后保存的位置</param>
- /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string DownloadFile(string saveFileFullName, string serverFileFullName, BackgroundWorker backgroundWorker = null)
- {
- return ReceiveFileCommandToServer(null, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, saveFileFullName, serverFileFullName, backgroundWorker);
- }
-
-
-
- /// <summary>
- /// 下载文件
- /// </summary>
- /// <param name="memoryMS">保存到指定的内存流中</param>
- /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string DownloadFile(MemoryStream memoryMS, string serverFileFullName, BackgroundWorker backgroundWorker = null)
- {
- return ReceiveFileCommandToServer(memoryMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", serverFileFullName, backgroundWorker);
- }
- /// <summary>
- /// 下载图像
- /// </summary>
- /// <param name="backgroundWorker"></param>
- /// <param name="resultBitmap">返回下载的图片</param>
- /// <param name="fileName">要下载的图片路径,以服务器程序的根目录定位 如“UpdateTemp\\test.jpg”</param>
- /// <returns></returns>
- public string DownloadBitmap(ref System.Drawing.Bitmap resultBitmap, string fileName, BackgroundWorker backgroundWorker = null)
- {
- try
- {
- string retMsg = "";
- if (LYFZ.WinAPI.CustomPublicMethod.ExistsImgage(fileName))
- {
- MemoryStream ImageMS = new MemoryStream();
- retMsg = ReceiveFileCommandToServer(ImageMS, HPSocketCS.Extended.TransferRequestCommand.DownloadFile, "", fileName, backgroundWorker);
- if (retMsg.Contains("成功"))
- {
- try
- {
- resultBitmap = new System.Drawing.Bitmap(ImageMS);
- }
- catch
- {
- retMsg = "下载失败,图像生成失败";
- }
- }
- else
- {
- if (retMsg.Trim() == "")
- {
- retMsg = "下载失败,请重试";
- }
- }
- ImageMS.Close();
- ImageMS.Dispose();
- }
- else
- {
- retMsg = "您请求下载的文件不是图片,不能下载";
- }
- return retMsg;
- }
- catch (Exception ex)
- {
- return "下载失败:" + ex.ToString();
- }
- }
- /// <summary>
- /// 向服务器上传文件
- /// </summary>
- /// <param name="command">上传命令</param>
- /// <param name="fileFullName">上传的文件全路径</param>
- /// <param name="toServerFileFullName">上传到服务器上的目录路径 以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="backgroundWorker">参数</param>
- /// <param name="memoryMS"></param>
- /// <param name="autoMainStoreDownload">如果是分店是否自动上传文件到总店服务器</param>
- /// <returns></returns>
- public string SendFileCommandToServer(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.UploadAvatar, string fileFullName = "", string toServerFileFullName = "", BackgroundWorker backgroundWorker = null, MemoryStream memoryMS = null)
- {
- string tempMsg = "";
- string fileName = toServerFileFullName;
- bool ret = false;
- TCP_NetworkClient myUploadClient = this.TFileClient;
-
- if (this.TFileClient.AppState != HPSocketCS.Extended.AppState.Started)
- {
- this.TFileClient.ConnectionServer();
- }
-
-
- if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
- {
- //如果是上传头像时设置头像路径
- toServerFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(toServerFileFullName);
- }
- if (myUploadClient.AppState == HPSocketCS.Extended.AppState.Started)
- {
- ServerFileInfo downloadFileInfo = myUploadClient.GetServerFileInfo(toServerFileFullName);
- bool isUpload = true;//是否需要上传文件 用于判断要上传的文件是否在服务器上存在,如果存在就不上传
- if (downloadFileInfo.IsExists)
- {
- if (downloadFileInfo.FileMd5.Trim().Length > 0)
- {
- if (memoryMS == null && fileFullName.Trim().Length > 0)
- {
- if (System.IO.File.Exists(fileFullName.Trim()))
- {
- FileInfo fi = new FileInfo(fileFullName.Trim());
- if (fi.Length < HPSocketCS.Sdk.FileMD5VerifySize)
- {
- string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(fileFullName.Trim());
- if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
- {
- isUpload = false;
- }
- }
- }
- }
- else if (memoryMS != null)
- {
- if (downloadFileInfo.FileMd5.Trim().Length > 0)
- {
- memoryMS.Position = 0;
- byte[] bytes = new byte[memoryMS.Length];
- memoryMS.Read(bytes, 0, bytes.Length);
- string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(bytes);
- Array.Clear(bytes, 0, bytes.Length);
- bytes = null;
- if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
- {
- isUpload = false;
- }
- }
- }
- }
- }
- if (isUpload)
- {
- if (fileFullName.Trim().Length > 0 && System.IO.File.Exists(fileFullName.Trim()) && memoryMS == null)
- {
- ret = myUploadClient.Client.UploadFiles(fileFullName.Trim(), toServerFileFullName, backgroundWorker);
- }
- else if (memoryMS != null)
- {
- ret = myUploadClient.Client.UploadMemoryStream(memoryMS, toServerFileFullName, backgroundWorker);
- }
- else
- {
- return "要上传的文件不存在:" + fileFullName;
- }
- }
- else
- {
- ret = true;
- }
- }
- else
- {
- return "网络连接失败,请检查网络环境";
- }
- if (ret)
- {
- tempMsg = "上传成功";
- }
- else
- {
- tempMsg = "上传失败";
- }
- return tempMsg;
- }
- /// <summary>
- /// 临时缓存文件目录
- /// </summary>
- static string TemporaryCachefilesPath = LYFZ.WinAPI.CustomPublicMethod.GetFullDirectoryPath(LYFZ.WinAPI.CustomPublicMethod.BasePath) + "Temp\\TemporaryCachefiles\\";
- // static bool isFileServerIng = false;
- /// <summary>
- /// 从服务器下载文件
- /// </summary>
- /// <param name="memoryMS"></param>
- /// <param name="command">下载命令</param>
- /// <param name="saveFileFullName">下载后要保存的文件全路</param>
- /// <param name="serverFileFullName">为你向服务器请求要下载的文件路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="backgroundWorker"></param>
- /// <param name="requestNumber">请求下载的次数 用于在下载失败时判断是否自动重新请求下载</param>
- /// <param name="autoMainStoreDownload">如果是分店是否自动到总店服务器下载文件</param>
- /// <returns></returns>
- public string ReceiveFileCommandToServer(MemoryStream memoryMS = null, HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar, string saveFileFullName = "", string serverFileFullName = "", BackgroundWorker backgroundWorker = null)
- {
- string tempMsg = "";
- // if (!isFileServerIng)
- {
- try
- {
- bool ret = false;
- TCP_NetworkClient myDownLoadClient = this.TFileClient;
- if (myDownLoadClient.AppState != HPSocketCS.Extended.AppState.Started)
- {
- myDownLoadClient.ConnectionServer();
- }
-
-
- if (myDownLoadClient.AppState == HPSocketCS.Extended.AppState.Started)
- {
- if (command == HPSocketCS.Extended.TransferRequestCommand.DownloadAvatar)
- {
- //如果是下载头像时设置头像在服务器上的路径
- serverFileFullName = "Resources\\Avatar\\User\\" + System.IO.Path.GetFileName(serverFileFullName);
- }
- ServerFileInfo downloadFileInfo = myDownLoadClient.GetServerFileInfo(serverFileFullName);
- if (downloadFileInfo.IsExists)
- {
- if (memoryMS == null && saveFileFullName.Trim().Length > 0)
- {
- if (downloadFileInfo.FileSize < HPSocketCS.Sdk.FileMD5VerifySize && downloadFileInfo.FileMd5.Trim().Length > 0 && System.IO.File.Exists(saveFileFullName.Trim()))
- {
- string saveFileMd5 = LYFZ.WinAPI.SDKSecurity.GetMD5HashFromFile(saveFileFullName.Trim());
- if (LYFZ.WinAPI.SDKSecurity.VerifyMd5Hash(downloadFileInfo.FileMd5.Trim(), saveFileMd5))
- {
- ret = true;
- }
- else
- {
- ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
- }
- }
- else
- {
- ret = myDownLoadClient.Client.DownloadFiles(serverFileFullName, saveFileFullName.Trim(), backgroundWorker);
- }
- }
- else if (memoryMS != null)
- {
- string TempCachefilePath = TemporaryCachefilesPath + downloadFileInfo.FileMd5 + "_" + System.IO.Path.GetFileName(serverFileFullName);
- byte[] TempCachefileBytes = null;
- bool TempCachefileExists = false;
- try
- {
- if (System.IO.File.Exists(TempCachefilePath))
- {
- TempCachefileBytes= System.IO.File.ReadAllBytes(TempCachefilePath);
- TempCachefileExists = true;
- }
- }
- catch { }
- if (!TempCachefileExists)
- {
- MemoryStream recMemoryMS = myDownLoadClient.Client.DownloadMemoryStream(serverFileFullName, backgroundWorker);
- if (recMemoryMS != null)
- {
- try
- {
- if (!System.IO.Directory.Exists(TemporaryCachefilesPath))
- {
- System.IO.Directory.CreateDirectory(TemporaryCachefilesPath);
- }
- recMemoryMS.Position = 0;
- byte[] bytes = new byte[recMemoryMS.Length];
- recMemoryMS.Read(bytes, 0, bytes.Length);
-
- System.IO.File.WriteAllBytes(TempCachefilePath, bytes);
- Array.Clear(bytes, 0, bytes.Length);
- bytes = null;
- }
- catch { }
- recMemoryMS.WriteTo(memoryMS);
- memoryMS.Position = 0;
- recMemoryMS.Close();
- recMemoryMS.Dispose();
- recMemoryMS = null;
- ret = true;
- }
- }
- else {
- memoryMS.Write(TempCachefileBytes, 0, TempCachefileBytes.Length);
- System.Array.Clear(TempCachefileBytes, 0, TempCachefileBytes.Length);
- TempCachefileBytes = null;
- ret = true;
- }
- }
- else
- {
- return "下载请求错误";
- }
- }
- else
- {
- return downloadFileInfo.GetMsg;
- }
- }
- else
- {
- return "网络连接失败,请检查网络环境";
- }
- if (ret)
- {
- tempMsg = "下载成功";
- }
- else
- {
- tempMsg = "下载失败";
- }
- }
- catch (Exception ex)
- {
- tempMsg = "下载出错:" + ex.Message;
- }
- // finally
- // {
- // isFileServerIng = false;
- // }
- }
- return tempMsg;
- }
- #endregion
-
- }
- }
|