12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.IO;
- using LYFZ.Network.EnumerateLibrary;
- using System.ComponentModel;
- using HPSocketCS.Extended;
- using System.Runtime.InteropServices;
- namespace LYFZ.Network.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);
- }
- this.Wapper = new TCP_RemoteDataHandlerPassiveMode(client);
- // 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>
- /// <param name="e"></param>
- /// <returns></returns>
- public delegate void EventVerifiedHandler(LYFZ.Network.TCPNetworkServer.EventLockVerified e);
- /// <summary>
- /// EventClientLockVerified事件
- /// </summary>
- public event EventVerifiedHandler EventClientVerified;
- /// <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:
- // string ReceiveInfo = Encoding.UTF8.GetString(recbytes, 0, recbytes.Length);
- // AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)>" + ReceiveInfo, sender.ConnectionId, bytes.Length));
-
- 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;
- case DataType.PushMessage:
- string ReceivePushMessage = Encoding.UTF8.GetString(recbytes, 0, recbytes.Length);
- TCP_ProtocolHelperXML Pushhelper = new TCP_ProtocolHelperXML(ReceivePushMessage.Trim());
- TCP_FileProtocol Pushprotocol = new TCP_FileProtocol();
- Pushprotocol = Pushhelper.GetProtocol();
- Pushprotocol.ReceiveFileSize = recbytes.Length;
- if (Pushprotocol.Content.Contains("VitalControl"))
- {
- string recValue = this.SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand.VitalControl, Pushprotocol.Content.Trim(), millisecondsTimeout: 9000);
- if (recValue.Trim().Contains("VitalControlOK"))
- {
- LYFZ.Network.TCPNetworkClient.TCP_NetworkClient.TServerClient.SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand.VitalControlOK, recValue.Trim(), millisecondsTimeout: 9000);
- }
- }
- break;
- case DataType.ShowForm:
- string ReceiveInfo = Encoding.UTF8.GetString(recbytes, 0, recbytes.Length);
- TCP_ProtocolHelperXML helper = new TCP_ProtocolHelperXML(ReceiveInfo.Trim());
- TCP_FileProtocol protocol = new TCP_FileProtocol();
- protocol = helper.GetProtocol();
- protocol.ReceiveFileSize = recbytes.Length;
- LYFZ.Network.TCPNetworkServer.EventLockVerified e = new TCPNetworkServer.EventLockVerified();
- e.CInfo.IpAddress = header.IPAddress;
- e.CInfo.Port =Convert.ToUInt16(header.Port);
- e.CInfo.Message = protocol.Content;
- if (this.EventClientVerified != null)
- {
- this.EventClientVerified(e);
- }
- 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();
- }
- /* string ReceiveInfo = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
- AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)>" + ReceiveInfo, sender.ConnectionId, bytes.Length));
- // AddMsg(string.Format(" > [{0},OnReceive] -> ({1} bytes)", sender.ConnectionId, bytes.Length));
- return HandleResult.Ok;*/
- }
- 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;
- }
- TCP_RemoteDataHandlerPassiveMode wapper = null;
- /// <summary>
- ///
- /// </summary>
- public TCP_RemoteDataHandlerPassiveMode Wapper
- {
- get { return this.wapper; }
- set { this.wapper = value; }
- }
- /// <summary>
- /// 刷新客户端连接
- /// </summary>
- /// <returns></returns>
- public bool RefreshClientList()
- {
- if (SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand.RefreshClientList).ToLower().Trim() == "ok")
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- /// <summary>
- /// 发送信息到客服端并返回服务器的处理结果
- /// </summary>
- /// <param name="msg"></param>
- /// <returns></returns>
- public string SendMsgToServer(string msg)
- {
- return SendCommandToServer(msgOrParameters: msg);
- }
- static string _FromServerStartTimeStamp = "";
- /// <summary>
- /// 来自服务器的启动时间标识
- /// </summary>
- public static string FromServerStartTimeStamp
- {
- get { return TCP_NetworkClient._FromServerStartTimeStamp; }
- set { TCP_NetworkClient._FromServerStartTimeStamp = value; }
- }
- /// <summary>
- /// 发送指令到服务端并返回服务器的处理结果
- /// </summary>
- /// <param name="command">要发送到服务器的指令</param>
- /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
- /// <returns></returns>
- public string SendCommandToServer(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello", int millisecondsTimeout = 1000*90)
- {
- string tempMsg = "";
- if (this.appState == AppState.Started)
- {
- tempMsg = this.Wapper.SendCommandToServerRetMessage(command, msgOrParameters, millisecondsTimeout);
- }
- return tempMsg;
- }
- /// <summary>
- /// 发送指令到服务端并返回服务器的处理结果
- /// </summary>
- /// <param name="command">要发送到服务器的指令</param>
- /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
- /// <returns></returns>
- public TCP_FileProtocol SendCommandToServerRetProtocol(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello")
- {
- TCP_FileProtocol protocol = new TCP_FileProtocol();
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- protocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, command, msgOrParameters);
- }
- return protocol;
- }
- /// <summary>
- /// 发送指令到服务端并返回二进制字节数组
- /// </summary>
- /// <param name="command">要发送到服务器的指令</param>
- /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
- /// <returns></returns>
- public byte[] DataCommandToServerRetByte(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello")
- {
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- TCP_FileProtocol protocol = DataCommandToServerProtocol(command, msgOrParameters);
- if (protocol.DataArray != null)
- {
- return protocol.DataArray;
- }
- else
- {
- return null;
- }
- }
- else
- {
- return null;
- }
- }
- /// <summary>
- /// 发送指令到服务端并返回二进制字节数组
- /// </summary>
- /// <param name="command">要发送到服务器的指令</param>
- /// <param name="msgOrParameters">发送到服务器指令的参数或是说明,注:多个参数用 “|”分隔</param>
- /// <returns></returns>
- public TCP_FileProtocol DataCommandToServerProtocol(HPSocketCS.Extended.TransferRequestCommand command = HPSocketCS.Extended.TransferRequestCommand.Message, string msgOrParameters = "Hello")
- {
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- return this.Wapper.HP_SendCommandToServer(InformationType.Data, command, msgOrParameters);
- }
- else
- {
- return new TCP_FileProtocol();
- }
- }
- /// <summary>
- /// 发送SQL指令到服务端并返回结果对象
- /// </summary>
- /// <param name="requestData"></param>
- /// <param name="millisecondsTimeout"></param>
- /// <returns></returns>
- public HPSocketCS.Extended.SQLHelperReturnData SqlCommandToServerReturnData(HPSocketCS.Extended.SQLHelperRequestData requestData, int millisecondsTimeout = 1000*90)
- {
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- return this.Wapper.HP_SendSqlCommandToServer(requestData, millisecondsTimeout);
- }
- else
- {
- return new SQLHelperReturnData("发送SQL指令到服务端时失败,网络连接已断开,请检查网络环境。");
- }
- }
- /// <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
- {
- TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.GetFileInfo, sFileName);
- 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="serverFileFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile.rar”</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string DeleteFile(string serverFileFullName, BackgroundWorker backgroundWorker = null, bool autoMainStoreDownload = true)
- {
- string ret = "删除失败";
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- try
- {
- TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.DeleteFile, serverFileFullName + "?" + autoMainStoreDownload.ToString());
- ret = sendFileProtocol.Content;
- }
- catch { ret = "连接已断开,请检查网络环境是否正常..."; }
- }
- return ret;
- }
- /// <summary>
- /// 删除服务上的目录
- /// </summary>
- /// <param name="serverDirectoryFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile”</param>
- /// <param name="backgroundWorker"></param>
- /// <returns></returns>
- public string DeleteDirectory(string serverDirectoryFullName, BackgroundWorker backgroundWorker = null, bool autoMainStoreDownload = true)
- {
- string ret = "删除失败";
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- try
- {
- serverDirectoryFullName = serverDirectoryFullName + "|false|" + autoMainStoreDownload.ToString();
- TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.DeleteDirectory, serverDirectoryFullName);
- ret = sendFileProtocol.Content;
- }
- catch { ret = "连接已断开,请检查网络环境是否正常..."; }
- }
- return ret;
- }
- /// <summary>
- /// 获取服务上的指定目录下的子目录集合
- /// </summary>
- /// <param name="retDirectoryList">返回的子目录集合</param>
- /// <param name="serverDirectoryFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile”</param>
- /// <param name="searchPattern">搜索条件</param>
- /// <param name="isSearchSubfolder">是否搜索子目录</param>
- /// <param name="backgroundWorker"></param>
- /// <param name="retDirectoryList">返回的目录集合</param>
- /// <returns></returns>
- public string GetDirectoryList(out List<string> retDirectoryList, string serverDirectoryFullName, string searchPattern = "*.*", bool isSearchSubfolder = false, BackgroundWorker backgroundWorker = null, bool autoMainStoreDownload = true)
- {
- string ret = "获取失败";
- retDirectoryList = new List<string>();
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- try
- {
- serverDirectoryFullName = serverDirectoryFullName + "|" + isSearchSubfolder.ToString() + "|" + searchPattern;
- if (!autoMainStoreDownload)
- {
- serverDirectoryFullName = serverDirectoryFullName + "|" + false.ToString();
- }
- TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.GetDirectoryList, serverDirectoryFullName);
- ret = sendFileProtocol.Content;
- if (ret.Contains("成功") && sendFileProtocol.ExtraInfo.Trim().Trim('|').Length > 0)
- {
- retDirectoryList.AddRange(sendFileProtocol.ExtraInfo.Trim().Trim('|').Split('|'));
- }
- }
- catch { ret = "连接已断开,请检查网络环境是否正常..."; }
- }
- return ret;
- }
- /// <summary>
- /// 获取服务上的指定目录下的文件集合
- /// </summary>
- /// <param name="retFileList">返回的文件集合</param>
- /// <param name="serverDirectoryFullName">要删除文件在服务器上的路径,以服务器程序的根目录定位 如“UpdateTemp\\testFile”</param>
- /// <param name="searchPattern">搜索条件</param>
- /// <param name="isSearchSubfolder">是否搜索子目录</param>
- /// <param name="backgroundWorker"></param>
- /// <param name="autoMainStoreDownload">是否自动连接总店服务器获取总店服务器上的信息</param>
- /// <param name="retDirectoryList">返回的目录集合</param>
- /// <returns></returns>
- public string GetDirectoryFileList(out List<string> retFileList, string serverDirectoryFullName, string searchPattern = "*.*", bool isSearchSubfolder = false, BackgroundWorker backgroundWorker = null, int millisecondsTimeout = 1000*90, bool autoMainStoreDownload = true)
- {
- string ret = "获取失败";
- retFileList = new List<string>();
- if (this.AppState == HPSocketCS.Extended.AppState.Started)
- {
- try
- {
- serverDirectoryFullName = serverDirectoryFullName + "|" + isSearchSubfolder.ToString() + "|" + searchPattern;
- if (!autoMainStoreDownload) {
- serverDirectoryFullName = serverDirectoryFullName + "|"+false.ToString();
- }
- TCP_FileProtocol sendFileProtocol = this.Wapper.HP_SendCommandToServer(InformationType.Message, HPSocketCS.Extended.TransferRequestCommand.GeTFileList, serverDirectoryFullName, millisecondsTimeout);
- ret = sendFileProtocol.Content;
- if (ret.Contains("成功") && sendFileProtocol.ExtraInfo.Trim().Trim('|').Length > 0)
- {
- retFileList.AddRange(sendFileProtocol.ExtraInfo.Trim().Trim('|').Split('|'));
- }
- }
- catch { ret = "连接已断开,请检查网络环境是否正常..."; }
- }
- return ret;
- }
- /// <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;
- }
- static TCP_NetworkClient tServerClient = null;
- public static TCP_NetworkClient TServerClient
- {
- get
- {
- if (TCP_NetworkClient.tServerClient == null)
- {
- TCP_NetworkClient.tServerClient = new TCP_NetworkClient();
- }
- return TCP_NetworkClient.tServerClient;
- }
- }
- #endregion
-
- }
- }
|