Exemple #1
0
        public static Task<ArraySegment<byte>> ReadBuffer(this Socket socket, int bufferSize)
        {
            var completionSource = new TaskCompletionSource<ArraySegment<byte>>();
            var buffer = new byte[bufferSize];
            var start = 0;
            AsyncCallback callback = null;
            callback = ar =>
            {
                int read;
                try
                {
                    read = socket.EndReceive(ar);
                    start += read;
                }
                catch (Exception e)
                {
                    completionSource.SetException(e);
                    return;
                }
                if (read == 0 || start == bufferSize)
                {
                    completionSource.SetResult(new ArraySegment<byte>(buffer, 0, start));
                    return;
                }
                socket.BeginReceive(buffer, start, bufferSize - start, SocketFlags.None, callback, null);
            };
            socket.BeginReceive(buffer, start, bufferSize - start, SocketFlags.Partial, callback, null);

            return completionSource.Task;
        }
Exemple #2
0
        /// <summary>
        /// Asynchronously receives data from a connected socket.
        /// </summary>
        /// <param name="socket">
        /// The socket from which to read data.
        /// </param>
        /// <param name="buffer">
        /// An array of type <see cref="byte"/> that is the storage location for
        /// the received data.
        /// </param>
        /// <param name="offset">
        /// The zero-based position in the <paramref name="buffer"/> parameter at which to
        /// start storing data.
        /// </param>
        /// <param name="size">
        /// The number of bytes to receive.
        /// </param>
        /// <param name="socketFlags">
        /// A bitwise combination of the <see cref="SocketFlags"/> values.
        /// </param>
        /// <returns>
        /// The number of bytes received.
        /// </returns>
        public static Task<int> ReceiveAsync(
            this Socket socket,
            byte[] buffer,
            int offset,
            int size,
            SocketFlags socketFlags)
        {
            var tcs = new TaskCompletionSource<int>(socket);

            socket.BeginReceive(
                buffer,
                offset,
                size,
                socketFlags,
                iar =>
                {
                    var t = (TaskCompletionSource<int>)iar.AsyncState;
                    var s = (Socket)t.Task.AsyncState;
                    try
                    {
                        t.TrySetResult(s.EndReceive(iar));
                    }
                    catch (Exception ex)
                    {
                        t.TrySetException(ex);
                    }
                },
                tcs);

            return tcs.Task;
        }
        public static void AsyncReceive(this Socket socket, byte[] buffer, object state, Action<int, object> callback)
        {
            if (state == null)
                throw new InvalidOperationException("State cannot be null");

            socket.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReceiveCallback), new State() { Socket = socket, Callback = new Callback(callback), UserDefinedState = state });
        }
        public static Task<int> ReceiveAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags = SocketFlags.None)
        {
            if (buffer == null) throw new ArgumentNullException("buffer");

            return Task<int>.Factory.FromAsync(
                (ac, state) => socket.BeginReceive(buffer, offset, size, flags, ac, state),
                socket.EndReceive,
                null,
                TaskCreationOptions.None);
        }
 public static Task<int> ReceiveAsync(this Socket socket, ArraySegment<byte> buffer, SocketFlags socketFlags)
 {
     return Task<int>.Factory.FromAsync(
         (callback, state) => socket.BeginReceive(
                                         buffer.Array, 
                                         buffer.Offset, 
                                         buffer.Count, 
                                         socketFlags, 
                                         callback, 
                                         state), 
         socket.EndReceive, null);
 }
		public static Task<int> ReceiveAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags, out SocketError error) {
			var tsc = new TaskCompletionSource<int> ();

			socket.BeginReceive (buffer, offset, size, flags, out error, asyncResult => {
				try {
					tsc.SetResult (socket.EndReceive (asyncResult));
				} catch (Exception e) {
					tsc.SetException (e);
				}
			}, null);

			return tsc.Task;
		}
        public static Task<int> ReceiveAsync(this Socket socket,
            byte[] buffer, int offset, int size, SocketFlags socketFlags)
        {
            if (socket == null) throw new ArgumentNullException(nameof(socket));

            var tcs = new TaskCompletionSource<int>();
            socket.BeginReceive(buffer, offset, size, socketFlags, ar =>
            {
                try { tcs.TrySetResult(socket.EndReceive(ar)); }
                catch (Exception e) { tcs.TrySetException(e);  }
            }, state: null);
            return tcs.Task;
        }
        public static async Task<UdpDatagram> ReceiveAsync(this UdpClient client)
        {
            byte[] bytes;
            IPEndPoint ipEndPoint = null;

            var task = Task.Factory
                .FromAsync<byte[]>(
                    (callback, state) => client.BeginReceive(callback, state),
                    (IAsyncResult asyncResult) => client.EndReceive(asyncResult, ref ipEndPoint), null);

            bytes = await task;

            return new UdpDatagram(ipEndPoint, bytes);
        }
        public static void AsyncReceiveFixed(this Socket socket, byte[] buffer, int offset, int len, OnReceived receivedCallback, object state)
        {
            socket.BeginReceive(buffer, offset, len, SocketFlags.None, ar =>
            {
                var received = socket.EndReceive(ar);
                if (received == 0)
                    receivedCallback.Invoke(state, null);

                if (received < len)
                    AsyncReceiveFixed(socket, buffer, offset + received, len - received, receivedCallback, state);
                else
                    receivedCallback.Invoke(state, buffer);

            }, state);
        }
Exemple #10
0
        internal static Task<int> ReceiveAsync(this Socket s, byte[] buffer, int offset, int count)
        {
            var tcs = new TaskCompletionSource<int>();

            s.BeginReceive(buffer, offset, count, SocketFlags.None, iasr =>
                {
                    try
                    {
                        tcs.SetResult(s.EndReceive(iasr));
                    }
                    catch (Exception e)
                    {
                        tcs.SetException(e);
                    }
                }, null);

            return tcs.Task;
        }
Exemple #11
0
        public static Task<int> ReceiveAsync(this Socket socket,
                                             byte[] buffer,
                                             int offset = 0,
                                             int size = 0,
                                             SocketFlags socketFlags = SocketFlags.None) {
            if(size <= 0)
                size = buffer.Length;

            var tcs = new TaskCompletionSource<int>();
            socket.BeginReceive(buffer, offset, size, socketFlags,
                                iar => {
                                    try {
                                        tcs.TrySetResult(socket.EndReceive(iar));
                                    }
                                    catch(Exception ex) {
                                        tcs.TrySetException(ex);
                                    }
                                }, null);

            return tcs.Task;
        }
Exemple #12
0
        public static Task<byte[]> RecieveAsyncTask(this Socket socket, CancellationTokenSource cancellationTokenSource)
        {
            var buff = new List<ArraySegment<byte>>();
            buff.Add(new ArraySegment<byte>(new byte[65535]));
            return Task<byte[]>.Factory.FromAsync(
                (ac, o) => socket.BeginReceive(buff, SocketFlags.None, ac, null),
                ar =>
                {
                    cancellationTokenSource.Token.ThrowIfCancellationRequested();
                    if (!socket.Connected)
                    {
                        throw new InvalidOperationException();
                    }
                    var length = socket.EndReceive(ar);
                    var result = new byte[length];
                    Array.Copy(buff[0].Array, result, length);
                    return result;

                },
                null);
        }
Exemple #13
0
        public static Task<int> ReceiveAsync(this Socket socket, byte[] buffer,
                                             int offset = 0, int size = -1,
                                             SocketFlags flags =
                                                 SocketFlags.None)
        {
            if (size < 0)
                size = buffer.Length;

            var source = new TaskCompletionSource<int>(socket);
            socket.BeginReceive(buffer, offset, size, flags, state =>
                {
                    try
                    {
                        source.SetResult(socket.EndReceive(state));
                    }
                    catch (Exception e)
                    {
                        source.SetException(e);
                    }
                }, source);
            return source.Task;
        }
 public static void ReceiveAPM(this Socket socket, byte[] buffer, int offset, int count, SocketFlags flags, Action<int> handler)
 {
     var callback = new AsyncCallback(asyncResult => handler(((Socket)asyncResult.AsyncState).EndReceive(asyncResult)));
     socket.BeginReceive(buffer, offset, count, flags, callback, socket);
 }
Exemple #15
0
 internal static IObservable<int> ReceiveAsync(this Socket s, byte[] buffer, int offset, int count)
 {
     return new AsyncOperation<int>(
         (c, st) => s.BeginReceive(buffer, offset, count, SocketFlags.None, c, st),
         iasr => { return s.EndReceive(iasr); });
 }
 public static void ReceiveBytesAsync(this Socket socket, byte[] bytes, int offset, int count, Action<byte[]> callback)
 {
     if (!MiscHelpers.Try(() => socket.BeginReceive(bytes, offset, count, SocketFlags.None, result => socket.OnBytesReceived(result, bytes, offset, count, callback), null)))
     {
         callback(null);
     }
 }
        /// <summary>
        /// Asynchronously receives data from a connected socket.
        /// </summary>
        /// <param name="socket">
        /// The socket from which to read data.
        /// </param>
        /// <param name="buffer">
        /// An array of type <see cref="byte"/> that is the storage location for
        /// the received data.
        /// </param>
        /// <param name="offset">
        /// The zero-based position in the <paramref name="buffer"/> parameter at which to
        /// start storing data.
        /// </param>
        /// <param name="size">
        /// The number of bytes to receive.
        /// </param>
        /// <param name="socketFlags">
        /// A bitwise combination of the <see cref="SocketFlags"/> values.
        /// </param>
        /// <param name="cancellationToken">
        /// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous task.
        /// </param>
        /// <remarks>
        /// Cancelling the task will also close the socket.
        /// </remarks>
        /// <returns>
        /// The number of bytes received.
        /// </returns>
        public static Task<int> ReceiveAsync(
            this Socket socket,
            byte[] buffer,
            int offset,
            int size,
            SocketFlags socketFlags,
            CancellationToken cancellationToken)
        {
            var tcs = new TaskCompletionSource<int>(socket);

            // Register a callback so that when a cancellation is requested, the socket is closed.
            // This will cause an ObjectDisposedException to bubble up via TrySetResult, which we can catch
            // and convert to a TaskCancelledException - which is the exception we expect.
            cancellationToken.Register(() => socket.Close());

            socket.BeginReceive(
                buffer,
                offset,
                size,
                socketFlags,
                iar =>
                {
                    var t = (TaskCompletionSource<int>)iar.AsyncState;
                    var s = (Socket)t.Task.AsyncState;
                    try
                    {
                        t.TrySetResult(s.EndReceive(iar));
                    }
                    catch (Exception ex)
                    {
                        // Did the cancellationToken's request for cancellation cause the socket to be closed
                        // and an ObjectDisposedException to be thrown? If so, indicate the caller that we were
                        // cancelled. If not, bubble up the original exception.
                        if (ex is ObjectDisposedException && cancellationToken.IsCancellationRequested)
                        {
                            t.TrySetCanceled();
                        }
                        else
                        {
                            t.TrySetException(ex);
                        }
                    }
                },
                tcs);

            return tcs.Task;
        }
        public static Task<Either<int, SocketError>> ReceiveNonBlocking(this Socket s, ArraySegment<byte> buf, SocketFlags flags)
        {
            SocketError err;

            var tcs = new TaskCompletionSource<Either<int, SocketError>>();

            try
            {
                IAsyncResult r = s.BeginReceive(buf.Array, buf.Offset, buf.Count, flags, out err, iar =>
                {
                    try
                    {
                        SocketError errInner;
                        int n = s.EndReceive(iar, out errInner);
                        if (n <= 0)
                            tcs.SetResult(errInner);
                        else
                            tcs.SetResult(n);
                    }
                    catch (SocketException skex)
                    {
                        tcs.SetResult(skex.SocketErrorCode);
                    }
                    catch (Exception ex)
                    {
                        tcs.SetException(ex);
                    }
                }, (object)null);

                if (r == null)
                    tcs.SetResult(err);
            }
            catch (SocketException skex)
            {
                tcs.SetResult(skex.SocketErrorCode);
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }

            return tcs.Task;
        }
Exemple #19
0
 public static Future<Network.UdpPacket> AsyncReceive(this UdpClient udpClient)
 {
     var f = new Future<Network.UdpPacket>();
     try {
         udpClient.BeginReceive((ar) => {
             IPEndPoint endpoint = default(IPEndPoint);
             try {
                 var bytes = udpClient.EndReceive(ar, ref endpoint);
                 f.Complete(new Network.UdpPacket(bytes, endpoint));
             } catch (FutureHandlerException) {
                 throw;
             } catch (Exception ex) {
                 f.Fail(ex);
             }
         }, null);
     } catch (Exception ex) {
         f.Fail(ex);
     }
     return f;
 }
        /// <summary>
        /// Extends BeginReceive so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginReceive(buffers, socketFlags, errorCode, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginReceive(this Socket socket, System.Collections.Generic.IList<ArraySegment<Byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback)
        {
            if(socket == null) throw new ArgumentNullException("socket");

            return socket.BeginReceive(buffers, socketFlags, out errorCode, callback, null);
        }
        /// <summary>
        /// Extends BeginReceive so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// socket.BeginReceive(buffer, socketFlags, errorCode, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginReceive(this Socket socket, Byte[] buffer, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback)
        {
            if(socket == null) throw new ArgumentNullException("socket");

            if(buffer == null) throw new ArgumentNullException("buffer");

            return socket.BeginReceive(buffer, 0, buffer.Length, socketFlags, out errorCode, callback);
        }
        /// <summary>
        /// Extends BeginReceive so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// socket.BeginReceive(buffer, offset, size, socketFlags, errorCode, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginReceive(this Socket socket, Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback)
        {
            if(socket == null) throw new ArgumentNullException("socket");

            return socket.BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, null);
        }
Exemple #23
0
 /// <summary>
 /// BeginReceive
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="buffer"></param>
 /// <param name="callback"></param>
 /// <returns></returns>
 public static IAsyncResult BeginReceive(this Socket socket, byte[] buffer, AsyncCallback callback) => socket.BeginReceive(buffer, callback, null);
 public static void ReceiveAPM(this Socket socket, IList<ArraySegment<byte>> buffers, SocketFlags flags, Action<int> handler)
 {
     var callback = new AsyncCallback(asyncResult => handler(((Socket)asyncResult.AsyncState).EndReceive(asyncResult)));
     socket.BeginReceive(buffers, flags, callback, socket);
 }
        /// <summary>
        /// Extends BeginReceive so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// udpclient.BeginReceive(requestCallback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginReceive(this UdpClient udpclient, AsyncCallback requestCallback)
        {
            if(udpclient == null) throw new ArgumentNullException("udpclient");

            return udpclient.BeginReceive(requestCallback, null);
        }
Exemple #26
0
 public static Task<int> ReceiveTaskAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags flags = SocketFlags.None)
 {
     return Task.Factory.FromAsync<int>(socket.BeginReceive(buffer, offset, size, flags, null, socket), socket.EndReceive);
 }
 public static async Task<int> ReceiveAsync(this Socket socket, byte[] buffer, int offset, int size, SocketFlags socketFlags)
 {
     return await Task<int>.Factory.FromAsync((callback, state) => socket.BeginReceive(buffer, offset, size, socketFlags, callback, state), ias => socket.EndReceive(ias), null);
 }
 public static void AsyncReceive(this Socket socket, byte[] buffer)
 {
     socket.BeginReceive(buffer, 0, buffer.Length, 0, new AsyncCallback(ReceiveCallback), new State() { Socket = socket, Callback = null });
 }
Exemple #29
0
        public static Task<int> ReceiveAsync(this Socket socket, byte[] buffer, int offset, int count, SocketFlags flags = SocketFlags.None)
        {
            if (socket == null)
                throw new ArgumentNullException("socket");

            var tcs = new TaskCompletionSource<int>();

            socket.BeginReceive(buffer, offset, count, flags, result =>
            {
                try
                {
                    var s = result.AsyncState as Socket;
                    var numberOfBytesReceived = s.EndReceive(result);

                    tcs.SetResult(numberOfBytesReceived);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex);
                }

            }, socket);

            return tcs.Task;
        }
Exemple #30
0
 /// <summary>
 /// BeginReceive
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="buffer"></param>
 /// <param name="callback"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 public static IAsyncResult BeginReceive(this Socket socket, byte[] buffer, AsyncCallback callback, object state) => socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, callback, state);