Skip to content

Instantly share code, notes, and snippets.

@mushfiqweb
Created April 25, 2017 00:50
Show Gist options
  • Save mushfiqweb/af43ed3bf41d6551d7034118b5584cea to your computer and use it in GitHub Desktop.
Save mushfiqweb/af43ed3bf41d6551d7034118b5584cea to your computer and use it in GitHub Desktop.
public static void Receive(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int received = 0; // how many bytes is already received
do {
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try {
received += socket.Receive(buffer, offset + received, size - received, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably empty, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (received < size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment