C#异步套接字文件传输

时间:2015-03-13 12:29:43

标签: c# sockets

我正在尝试编写一个C#服务器应用程序,该应用程序将从几个用C ++编写的客户端接收文件,主要问题是我对C#.Net很新。

设法为同步套接字C#服务器编写了一个代码,但无法弄清楚如何以字节方式接收异步套接字的数据并将其写入OnDataReceive回调内的单个文件。

public void OnDataReceived(IAsyncResult asyn)
{
  try
  {
    SocketPacket socketData = (SocketPacket)asyn.AsyncState;

    ////Original code inside this function
    //int iRx = socketData.m_currentSocket.EndReceive(asyn);
    //char[] chars = new char[iRx + 1];
    //System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
    //int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);
    //System.String szData = new System.String(chars);
    //richTextBoxReceivedMsg.AppendText(szData);

    ////My old code from Sync socket file transfer
    //Receive data from client socket till it continues
    byte[] bufferData = new byte[1024];
    int recvBytesLen = 0;
    BinaryWriter bWrite = new BinaryWriter(File.Open(m_strCurrFolder + "File", FileMode.Append));
    do
    {
      recvBytesLen = clientSock.Receive(bufferData, bufferData.Length, 0);
      bWrite.Write(bufferData, 0, recvBytesLen);
    } while (recvBytesLen > 0);

    //Closing file and socket once done
    bWrite.Close();

    // Continue the waiting for data on the Socket
    WaitForData(socketData.m_currentSocket);
  }
  catch (ObjectDisposedException)
  {
    System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
  }
  catch (SocketException se)
  {
    MessageBox.Show(se.Message);
  }
}

1 个答案:

答案 0 :(得分:1)

发现此链接有帮助并完成我的工作。 https://code.msdn.microsoft.com/windowsapps/Fixed-size-large-file-dfc3f45d

private static void ReceiveCallback(IAsyncResult ar) 
 { 
     StateObject state = (StateObject)ar.AsyncState; 
     Socket clientSocket = state.WorkSocket; 
     BinaryWriter writer; 


     int bytesRead = clientSocket.EndReceive(ar); 
     if (bytesRead > 0) 
     { 
         //If the file doesn't exist, create a file with the filename got from server. If the file exists, append to the file. 
         if (!File.Exists(fileSavePath)) 
         { 
             writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Create)); 
         } 
         else 
         { 
             writer = new BinaryWriter(File.Open(fileSavePath, FileMode.Append)); 
         } 


         writer.Write(state.Buffer, 0, bytesRead); 
         writer.Flush(); 
         writer.Close(); 


         // Notify the progressBar to change the position. 
         Client.BeginInvoke(new ProgressChangeHandler(Client.ProgressChanged)); 


         // Recursively receive the rest file. 
         try 
         { 
             clientSocket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); 
         } 
         catch 
         { 
             if (!clientSocket.Connected) 
             { 
                 MessageBox.Show(Properties.Resources.DisconnectMsg); 
             } 
         } 
     } 
     else 
     { 
         // Signal if all the file received. 
         receiveDone.Set(); 
     } 
 }