SHARE
TWEET

Untitled

a guest Jun 24th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. private static async Task ReceiveDataFromRemoteSocket(
  2.     Socket socket,
  3.     int numBytesExpectedToReceive)
  4. {
  5.     int numBytesLeftToReceive = numBytesExpectedToReceive;
  6.  
  7.     using (MemoryStream memoryStream = new MemoryStream(numBytesExpectedToReceive))
  8.     {
  9.         byte[] dataBuffer = new byte[1024];
  10.  
  11.         ArraySegment<byte> dataBufferSegment = new ArraySegment<byte>(dataBuffer);          
  12.         int totalBytesReceived = 0;
  13.  
  14.         while (numBytesLeftToReceive > 0)
  15.         {
  16.             Array.Clear(dataBuffer, 0, dataBuffer.Length);
  17.  
  18.             int numBytesReceived = await socket.ReceiveAsync(dataBufferSegment, SocketFlags.Partial);
  19.             Console.WriteLine($"Received {numBytesReceived} bytes of data at {DateTime.UtcNow.ToShortTimeString()}.");
  20.  
  21.             totalBytesReceived += numBytesReceived;
  22.  
  23.             memoryStream.Write(
  24.                 dataBuffer,
  25.                 0,
  26.                 numBytesLeftToReceive < dataBuffer.Length ? numBytesLeftToReceive : dataBuffer.Length);
  27.             numBytesLeftToReceive -= numBytesReceived;
  28.         }
  29.         Console.WriteLine($"Total number of bytes received, according to tally: {totalBytesReceived}.");
  30.         Console.WriteLine($"Memory stream: Contains {memoryStream.Length} bytes' worth of data.");
  31.     }
  32. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top