C#高性能大容量SOCKET并发(十一):编写上传客户端
客戶端封裝整體框架
客戶端編程基于阻塞同步模式,只有數據正常發送或接收才返回,如果發生錯誤則拋出異常,基于TcpClient進行封裝,主要類結構如下圖:
TcpClient:NET系統封裝,實現了底層Socket操作,提供了阻塞和非阻塞調用;
OutgoingDataAssembler m_outgoingDataAssembler:協議組裝器,用來組裝往外發送的命令,主要用于組裝協議格式;
DynamicBufferManager m_sendBuffer:用于把命令和數據同時寫入到緩存中,調用一次發送,這樣服務器就只會產生一次IOCP回調,可以提高性能;
IncomingDataParser m_incomingDataParser:收到數據的解析器,用于解析返回的內容,主要是解析文本格式;
protected DynamicBufferManager m_recvBuffer:接收數據的緩存,數據存到緩存中后,可以解析命令和數據;
TcpClient說明,阻塞和非阻塞
TcpClient封裝了NET的底層Socket操作,基于TCP協議,提供了阻塞和非阻塞模式調用,具體是設置m_tcpClient.Client.Blocking = true表示使用阻塞模式,反之則使用非阻塞模式。阻塞模式表示接收完指定長度的數據才返回,非阻塞模式表示收到一點數據就返回。
如我們調用m_tcpClient.Client.Receive(m_recvBuffer.Buffer, sizeof(int), packetLength, SocketFlags.None),假設傳入的長度為1024,阻塞模式一點要等到數據達到1024長度才返回,否則一直等待Socket超時或者鏈路斷了,非阻塞模式則不同,加入收到8字節了,則返回調用者,調用者使用循環繼續接受1024-8=1016的數據。
發送命令
發送數據和服務端相同,主要是對數據進行組包,然后調用發送函數發送,具體代碼如下:
public void SendCommand(byte[] buffer, int offset, int count){string commandText = m_outgoingDataAssembler.GetProtocolText();byte[] bufferUTF8 = Encoding.UTF8.GetBytes(commandText);int totalLength = sizeof(int) + bufferUTF8.Length + count; //獲取總大小m_sendBuffer.Clear();m_sendBuffer.WriteInt(totalLength, false); //寫入總大小m_sendBuffer.WriteInt(bufferUTF8.Length, false); //寫入命令大小m_sendBuffer.WriteBuffer(bufferUTF8); //寫入命令內容m_sendBuffer.WriteBuffer(buffer, offset, count); //寫入二進制數據m_tcpClient.Client.Send(m_sendBuffer.Buffer, 0, m_sendBuffer.DataCount, SocketFlags.None);}
接收命令
接收命令和發送相反,先接收長度,然后接收內容,然后對數據進行解包,具體代碼如下:
public bool RecvCommand(out byte[] buffer, out int offset, out int size){m_recvBuffer.Clear();m_tcpClient.Client.Receive(m_recvBuffer.Buffer, sizeof(int), SocketFlags.None);int packetLength = BitConverter.ToInt32(m_recvBuffer.Buffer, 0); //獲取包長度if (NetByteOrder)packetLength = System.Net.IPAddress.NetworkToHostOrder(packetLength); //把網絡字節順序轉為本地字節順序m_recvBuffer.SetBufferSize(sizeof(int) + packetLength); //保證接收有足夠的空間m_tcpClient.Client.Receive(m_recvBuffer.Buffer, sizeof(int), packetLength, SocketFlags.None);int commandLen = BitConverter.ToInt32(m_recvBuffer.Buffer, sizeof(int)); //取出命令長度string tmpStr = Encoding.UTF8.GetString(m_recvBuffer.Buffer, sizeof(int) + sizeof(int), commandLen);if (!m_incomingDataParser.DecodeProtocolText(tmpStr)) //解析命令{buffer = null;offset = 0;size = 0;return false;}else{buffer = m_recvBuffer.Buffer;offset = commandLen + sizeof(int) + sizeof(int);size = packetLength - offset;return true;}}
命令交互
封裝了底層Socket操作和協議解析后,實現一個命令交互如登錄代碼如下:
public bool DoLogin(string userName, string password){try{m_outgoingDataAssembler.Clear();m_outgoingDataAssembler.AddRequest();m_outgoingDataAssembler.AddCommand(AsyncSocketServer.ProtocolKey.Login);m_outgoingDataAssembler.AddValue(AsyncSocketServer.ProtocolKey.UserName, userName);m_outgoingDataAssembler.AddValue(AsyncSocketServer.ProtocolKey.Password, AsyncSocketServer.BasicFunc.MD5String(password));SendCommand();bool bSuccess = RecvCommand();if (bSuccess){bSuccess = CheckErrorCode();if (bSuccess){m_userName = userName;m_password = password;}return bSuccess;}elsereturn false;}catch (Exception E){//記錄日志m_errorString = E.Message;return false;}}
上傳協議
上傳協議主要分為三個命令,第一個是Upload,向服務器請求上傳的文件,如果服務器有相同的文件,則返回是否傳完,如果未傳完,返回需要續傳的文件位置,然后客戶端則從上一個位置開始傳輸,傳輸數據服務器只接收,不應答,客戶端傳輸完后,發完成(EOF)命令。因此三個命令封裝代碼如下:
public bool DoUpload(string dirName, string fileName, ref long fileSize){bool bConnect = ReConnectAndLogin(); //檢測連接是否還在,如果斷開則重連并登錄if (!bConnect)return bConnect;try{m_outgoingDataAssembler.Clear();m_outgoingDataAssembler.AddRequest();m_outgoingDataAssembler.AddCommand(AsyncSocketServer.ProtocolKey.Upload);m_outgoingDataAssembler.AddValue(AsyncSocketServer.ProtocolKey.DirName, dirName);m_outgoingDataAssembler.AddValue(AsyncSocketServer.ProtocolKey.FileName, fileName);SendCommand();bool bSuccess = RecvCommand();if (bSuccess){bSuccess = CheckErrorCode();if (bSuccess){bSuccess = m_incomingDataParser.GetValue(AsyncSocketServer.ProtocolKey.FileSize, ref fileSize);}return bSuccess;}elsereturn false;}catch (Exception E){//記錄日志m_errorString = E.Message;return false;}}public bool DoData(byte[] buffer, int offset, int count){try{m_outgoingDataAssembler.Clear();m_outgoingDataAssembler.AddRequest();m_outgoingDataAssembler.AddCommand(AsyncSocketServer.ProtocolKey.Data);SendCommand(buffer, offset, count);return true;}catch (Exception E){//記錄日志m_errorString = E.Message;return false;}}public bool DoEof(Int64 fileSize){try{m_outgoingDataAssembler.Clear();m_outgoingDataAssembler.AddRequest();m_outgoingDataAssembler.AddCommand(AsyncSocketServer.ProtocolKey.Eof);SendCommand();bool bSuccess = RecvCommand();if (bSuccess)return CheckErrorCode();elsereturn false;}catch (Exception E){//記錄日志m_errorString = E.Message;return false;}}調用過程:
protected static bool SendFile(string fileName, ClientUploadSocket uploadSocket){FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite);try{try{long fileSize = 0;if (!uploadSocket.DoUpload("", Path.GetFileName(fileName), ref fileSize))throw new Exception(uploadSocket.ErrorString);fileStream.Position = fileSize;byte[] readBuffer = new byte[PacketSize];while (fileStream.Position < fileStream.Length){int count = fileStream.Read(readBuffer, 0, PacketSize);if (!uploadSocket.DoData(readBuffer, 0, count))throw new Exception(uploadSocket.ErrorString);}if (!uploadSocket.DoEof(fileStream.Length))throw new Exception(uploadSocket.ErrorString);return true;}catch (Exception E){Console.WriteLine("Upload File Error: " + E.Message);return false;}}finally{fileStream.Close();}}
DEMO下載地址:http://download.csdn.net/detail/sqldebug_fan/7467745
免責聲明:此代碼只是為了演示C#完成端口編程,僅用于學習和研究,切勿用于商業用途。水平有限,C#也屬于初學,錯誤在所難免,歡迎指正和指導。郵箱地址:fansheng_hx@163.com。
總結
以上是生活随笔為你收集整理的C#高性能大容量SOCKET并发(十一):编写上传客户端的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql server 2005 expr
- 下一篇: exportfs+NFS客户端问题