From ceb831b18ffe47c961d9a176ac077988193171d9 Mon Sep 17 00:00:00 2001 From: sta Date: Mon, 7 Sep 2015 21:51:49 +0900 Subject: [PATCH] [Modify] Add readBytesAsync method Merge a part of pull request #153 from https://github.com/cswiedler/websocket-sharp/commit/fd5fc9a5fc5fa8d993a150e40c9eeb1a02138c27. --- websocket-sharp/Ext.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) 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++)