private async Task<byte[]> ReceiveExactly(int count)
{
var buffer = new byte[count];
if (count == 0)
return buffer;
var readCount = 0;
while (readCount < count)
{
var remainingCount = count - readCount;
readCount += await Task.Factory.FromAsync<int>(
socket.BeginReceive(buffer, readCount, remainingCount, SocketFlags.None, null, null), socket.EndReceive);
}
if (readCount != count)
throw new InvalidOperationException();
return buffer;
}
}