diff --git a/websocket-sharp/Ext.cs b/websocket-sharp/Ext.cs index ffffd704..055a7718 100644 --- a/websocket-sharp/Ext.cs +++ b/websocket-sharp/Ext.cs @@ -41,6 +41,7 @@ * Contributors: * - Liryna * - Nikola Kovacevic + * - Chris Swiedler */ #endregion @@ -161,6 +162,40 @@ namespace WebSocketSharp return cnt < count ? buffer.SubArray (0, offset + cnt) : buffer; } + private static void readBytesAsync ( + this Stream stream, + byte[] buffer, + int offset, + int count, + Action completed, + Action 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) { for (ulong i = 0; i < n; i++)