[Modify] Add readBytesAsync method

Merge a part of pull request #153 from fd5fc9a5fc.
This commit is contained in:
sta 2015-09-07 21:51:49 +09:00
parent 75412101d8
commit ceb831b18f

View File

@ -41,6 +41,7 @@
* Contributors: * Contributors:
* - Liryna <liryna.stark@gmail.com> * - Liryna <liryna.stark@gmail.com>
* - Nikola Kovacevic <nikolak@outlook.com> * - Nikola Kovacevic <nikolak@outlook.com>
* - Chris Swiedler
*/ */
#endregion #endregion
@ -161,6 +162,40 @@ namespace WebSocketSharp
return cnt < count ? buffer.SubArray (0, offset + cnt) : buffer; return cnt < count ? buffer.SubArray (0, offset + cnt) : buffer;
} }
private static void readBytesAsync (
this Stream stream,
byte[] buffer,
int offset,
int count,
Action<byte[]> completed,
Action<Exception> error)
{
AsyncCallback callback = ar => {
try {
var nread = stream.EndRead (ar);
if (nread < 1) {
// EOF/Disconnect before reading specified number of bytes.
completed (buffer.SubArray (0, offset));
return;
}
if (nread < count) {
// Need to read more.
stream.readBytesAsync (buffer, offset + nread, count - nread, completed, error);
return;
}
completed (buffer);
}
catch (Exception ex) {
if (error != null)
error (ex);
}
};
stream.BeginRead (buffer, offset, count, callback, null);
}
private static void times (this ulong n, Action action) private static void times (this ulong n, Action action)
{ {
for (ulong i = 0; i < n; i++) for (ulong i = 0; i < n; i++)