Example #1
0
        internal IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
        {
            if (s_loggingEnabled)
            {
                Logging.Enter(Logging.Sockets, this, "BeginReceiveMessageFrom", "");
            }
            GlobalLog.Print("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString());

            if (CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (remoteEP == null)
            {
                throw new ArgumentNullException("remoteEP");
            }
            if (!CanTryAddressFamily(remoteEP.AddressFamily))
            {
                throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), "remoteEP");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }
            if (_rightEndPoint == null)
            {
                throw new InvalidOperationException(SR.net_sockets_mustbind);
            }


            // Set up the result and set it to collect the context.
            ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
            asyncResult.StartPostingAsyncOp(false);

            // Start the ReceiveFrom.
            EndPoint oldEndPoint = _rightEndPoint;

            // We don't do a CAS demand here because the contents of remoteEP aren't used by
            // WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress
            // with the right address family
            Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);

            // Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
            // avoid a Socket leak in case of error.
            SocketError errorCode = SocketError.SocketError;
            try
            {
                // Save a copy of the original EndPoint in the asyncResult.
                asyncResult.SocketAddressOriginal = IPEndPointExtensions.Serialize(remoteEP);

                SetReceivingPacketInformation();

                if (_rightEndPoint == null)
                {
                    _rightEndPoint = remoteEP;
                }

                errorCode = SocketPal.ReceiveMessageFromAsync(this, _handle, buffer, offset, size, socketFlags, socketAddress, asyncResult);

                if (errorCode != SocketError.Success)
                {
                    // WSARecvMsg() will never return WSAEMSGSIZE directly, since a completion is queued in this case.  We wouldn't be able
                    // to handle this easily because of assumptions OverlappedAsyncResult makes about whether there would be a completion
                    // or not depending on the error code.  If WSAEMSGSIZE would have been normally returned, it returns WSA_IO_PENDING instead.
                    // That same map is implemented here just in case.
                    if (errorCode == SocketError.MessageSize)
                    {
                        GlobalLog.Assert("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom()|Returned WSAEMSGSIZE!");
                        errorCode = SocketError.IOPending;
                    }
                }

                GlobalLog.Print("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom() Interop.Winsock.WSARecvMsg returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + Logging.HashString(asyncResult));
            }
            catch (ObjectDisposedException)
            {
                _rightEndPoint = oldEndPoint;
                throw;
            }
            finally
            {
                errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
            }

            // Throw an appropriate SocketException if the native call fails synchronously.
            if (errorCode != SocketError.Success)
            {
                // Update the internal state of this socket according to the error before throwing.
                _rightEndPoint = oldEndPoint;
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (s_loggingEnabled)
                {
                    Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", socketException);
                }
                throw socketException;
            }

            // Capture the context, maybe call the callback, and return.
            asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);

            if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress))
            {
                try
                {
                    remoteEP = remoteEP.Create(asyncResult.SocketAddress);
                }
                catch
                {
                }
            }

            GlobalLog.Print("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString() + " returning AsyncResult:" + Logging.HashString(asyncResult));
            if (s_loggingEnabled)
            {
                Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", asyncResult);
            }
            return asyncResult;
        }
Example #2
0
 /// <summary>
 /// Begins to asynchronously receive the specified number of bytes of data into the specified location of the data buffer, using the specified <see cref="T:System.Net.Sockets.SocketFlags"/>, and stores the endpoint and packet information..
 /// </summary>
 /// 
 /// <returns>
 /// An <see cref="T:System.IAsyncResult"/> that references the asynchronous read.
 /// </returns>
 /// <param name="buffer">An array of type <see cref="T:System.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 store the data.</param><param name="size">The number of bytes to receive. </param><param name="socketFlags">A bitwise combination of the <see cref="T:System.Net.Sockets.SocketFlags"/> values.</param><param name="remoteEP">An <see cref="T:System.Net.EndPoint"/> that represents the source of the data.</param><param name="callback">The <see cref="T:System.AsyncCallback"/> delegate.</param><param name="state">An object that contains state information for this request.</param><exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null.-or- <paramref name="remoteEP"/> is null. </exception><exception cref="T:System.Net.Sockets.SocketException">An error occurred when attempting to access the socket. See the Remarks section for more information. </exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset"/> is less than 0.-or- <paramref name="offset"/> is greater than the length of <paramref name="buffer"/>.-or- <paramref name="size"/> is less than 0.-or- <paramref name="size"/> is greater than the length of <paramref name="buffer"/> minus the value of the <paramref name="offset"/> parameter. </exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.NotSupportedException">The operating system is Windows 2000 or earlier, and this method requires Windows XP.</exception>
 public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
 {
     if (Socket.s_LoggingEnabled)
     Logging.Enter(Logging.Sockets, (object) this, "BeginReceiveMessageFrom", "");
       if (this.CleanedUp)
     throw new ObjectDisposedException(this.GetType().FullName);
       if (buffer == null)
     throw new ArgumentNullException("buffer");
       if (remoteEP == null)
     throw new ArgumentNullException("remoteEP");
       if (!this.CanTryAddressFamily(remoteEP.AddressFamily))
       {
     throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", (object) remoteEP.AddressFamily, (object) this.addressFamily), "remoteEP");
       }
       else
       {
     if (offset < 0 || offset > buffer.Length)
       throw new ArgumentOutOfRangeException("offset");
     if (size < 0 || size > buffer.Length - offset)
       throw new ArgumentOutOfRangeException("size");
     if (this.m_RightEndPoint == null)
       throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
     ReceiveMessageOverlappedAsyncResult overlappedAsyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
     overlappedAsyncResult.StartPostingAsyncOp(false);
     EndPoint endPoint = this.m_RightEndPoint;
     SocketAddress socketAddress = this.SnapshotAndSerialize(ref remoteEP);
     SocketError socketError = SocketError.SocketError;
     try
     {
       overlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref this.Caches.ReceiveOverlappedCache);
       overlappedAsyncResult.SocketAddressOriginal = remoteEP.Serialize();
       this.SetReceivingPacketInformation();
       if (this.m_RightEndPoint == null)
     this.m_RightEndPoint = remoteEP;
       int bytesTransferred;
       socketError = this.WSARecvMsg(this.m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement((Array) overlappedAsyncResult.m_MessageBuffer, 0), out bytesTransferred, overlappedAsyncResult.OverlappedHandle, IntPtr.Zero);
       if (socketError != SocketError.Success)
       {
     socketError = (SocketError) Marshal.GetLastWin32Error();
     if (socketError == SocketError.MessageSize)
       socketError = SocketError.IOPending;
       }
     }
     catch (ObjectDisposedException ex)
     {
       this.m_RightEndPoint = endPoint;
       throw;
     }
     finally
     {
       socketError = overlappedAsyncResult.CheckAsyncCallOverlappedResult(socketError);
     }
     if (socketError != SocketError.Success)
     {
       this.m_RightEndPoint = endPoint;
       overlappedAsyncResult.ExtractCache(ref this.Caches.ReceiveOverlappedCache);
       SocketException socketException = new SocketException(socketError);
       this.UpdateStatusAfterSocketError(socketException);
       if (Socket.s_LoggingEnabled)
     Logging.Exception(Logging.Sockets, (object) this, "BeginReceiveMessageFrom", (Exception) socketException);
       throw socketException;
     }
     else
     {
       overlappedAsyncResult.FinishPostingAsyncOp(ref this.Caches.ReceiveClosureCache);
       if (overlappedAsyncResult.CompletedSynchronously)
       {
     if (!overlappedAsyncResult.SocketAddressOriginal.Equals((object) overlappedAsyncResult.SocketAddress))
     {
       try
       {
         remoteEP = remoteEP.Create(overlappedAsyncResult.SocketAddress);
       }
       catch
       {
       }
     }
       }
       if (Socket.s_LoggingEnabled)
     Logging.Exit(Logging.Sockets, (object) this, "BeginReceiveMessageFrom", (object) overlappedAsyncResult);
       return (IAsyncResult) overlappedAsyncResult;
     }
       }
 }
Example #3
0
        public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) {
            if (s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "BeginReceiveMessageFrom", "");
            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString());

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (buffer==null) {
                throw new ArgumentNullException("buffer");
            }
            if (remoteEP==null) {
                throw new ArgumentNullException("remoteEP");
            }
            if (!CanTryAddressFamily(remoteEP.AddressFamily)) {
                throw new ArgumentException(SR.GetString(SR.net_InvalidEndPointAddressFamily, 
                    remoteEP.AddressFamily, addressFamily), "remoteEP");
            }
            if (offset<0 || offset>buffer.Length) {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size<0 || size>buffer.Length-offset) {
                throw new ArgumentOutOfRangeException("size");
            }
            if (m_RightEndPoint==null) {
                throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustbind));
            }


            // Set up the result and set it to collect the context.
            ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
            asyncResult.StartPostingAsyncOp(false);

            // Start the ReceiveFrom.
            EndPoint oldEndPoint = m_RightEndPoint;

            // We don't do a CAS demand here because the contents of remoteEP aren't used by
            // WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress
            // with the right address family
            SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);

            // Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to
            // avoid a Socket leak in case of error.
            SocketError errorCode = SocketError.SocketError;
            try
            {
                asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref Caches.ReceiveOverlappedCache);

                // save a copy of the original EndPoint in the asyncResult
                asyncResult.SocketAddressOriginal = remoteEP.Serialize();

                int bytesTransfered;

                SetReceivingPacketInformation();

                if (m_RightEndPoint == null)
                {
                    m_RightEndPoint = remoteEP;
                }

                errorCode = (SocketError) WSARecvMsg(
                    m_Handle,
                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.m_MessageBuffer,0),
                    out bytesTransfered,
                    asyncResult.OverlappedHandle,
                    IntPtr.Zero);

                if (errorCode!=SocketError.Success) {
                    errorCode = (SocketError)Marshal.GetLastWin32Error();

                    // I have guarantees from Brad Williamson that WSARecvMsg() will never return WSAEMSGSIZE directly, since a completion
                    // is queued in this case.  We wouldn't be able to handle this easily because of assumptions OverlappedAsyncResult
                    // makes about whether there would be a completion or not depending on the error code.  If WSAEMSGSIZE would have been
                    // normally returned, it returns WSA_IO_PENDING instead.  That same map is implemented here just in case.
                    if (errorCode == SocketError.MessageSize)
                    {
                        GlobalLog.Assert("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom()|Returned WSAEMSGSIZE!");
                        errorCode = SocketError.IOPending;
                    }
                }

                GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom() UnsafeNclNativeMethods.OSSOCK.WSARecvMsg returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));
            }
            catch (ObjectDisposedException)
            {
                m_RightEndPoint = oldEndPoint;
                throw;
            }
            finally
            {
                errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
            }

            //
            // if the asynchronous native call fails synchronously
            // we'll throw a SocketException
            //
            if (errorCode!=SocketError.Success)
            {
                //
                // update our internal state after this socket error and throw
                //
                m_RightEndPoint = oldEndPoint;
                asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
                SocketException socketException = new SocketException(errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (s_LoggingEnabled) Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", socketException);
                throw socketException;
            }

            // Capture the context, maybe call the callback, and return.
            asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);

            if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress)) {
                try {
                    remoteEP = remoteEP.Create(asyncResult.SocketAddress);
                }
                catch {
                }
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));
            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", asyncResult);
            return asyncResult;
        }
 public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
 {
     if (s_LoggingEnabled)
     {
         Logging.Enter(Logging.Sockets, this, "BeginReceiveMessageFrom", "");
     }
     if (this.CleanedUp)
     {
         throw new ObjectDisposedException(base.GetType().FullName);
     }
     if (!ComNetOS.IsPostWin2K)
     {
         throw new PlatformNotSupportedException(SR.GetString("WinXPRequired"));
     }
     if (buffer == null)
     {
         throw new ArgumentNullException("buffer");
     }
     if (remoteEP == null)
     {
         throw new ArgumentNullException("remoteEP");
     }
     if (remoteEP.AddressFamily != this.addressFamily)
     {
         throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", new object[] { remoteEP.AddressFamily, this.addressFamily }), "remoteEP");
     }
     if ((offset < 0) || (offset > buffer.Length))
     {
         throw new ArgumentOutOfRangeException("offset");
     }
     if ((size < 0) || (size > (buffer.Length - offset)))
     {
         throw new ArgumentOutOfRangeException("size");
     }
     if (this.m_RightEndPoint == null)
     {
         throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
     }
     ReceiveMessageOverlappedAsyncResult retObject = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
     retObject.StartPostingAsyncOp(false);
     EndPoint rightEndPoint = this.m_RightEndPoint;
     EndPoint point2 = remoteEP;
     SocketAddress socketAddress = this.SnapshotAndSerialize(ref point2);
     SocketError socketError = SocketError.SocketError;
     try
     {
         int num;
         retObject.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref this.Caches.ReceiveOverlappedCache);
         retObject.SocketAddressOriginal = point2.Serialize();
         this.SetReceivingPacketInformation();
         if (this.m_RightEndPoint == null)
         {
             this.m_RightEndPoint = point2;
         }
         socketError = this.WSARecvMsg(this.m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement(retObject.m_MessageBuffer, 0), out num, retObject.OverlappedHandle, IntPtr.Zero);
         if (socketError != SocketError.Success)
         {
             socketError = (SocketError) Marshal.GetLastWin32Error();
             if (socketError == SocketError.MessageSize)
             {
                 socketError = SocketError.IOPending;
             }
         }
     }
     catch (ObjectDisposedException)
     {
         this.m_RightEndPoint = rightEndPoint;
         throw;
     }
     finally
     {
         socketError = retObject.CheckAsyncCallOverlappedResult(socketError);
     }
     if (socketError != SocketError.Success)
     {
         this.m_RightEndPoint = rightEndPoint;
         retObject.ExtractCache(ref this.Caches.ReceiveOverlappedCache);
         SocketException socketException = new SocketException(socketError);
         this.UpdateStatusAfterSocketError(socketException);
         if (s_LoggingEnabled)
         {
             Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", socketException);
         }
         throw socketException;
     }
     retObject.FinishPostingAsyncOp(ref this.Caches.ReceiveClosureCache);
     if (retObject.CompletedSynchronously && !retObject.SocketAddressOriginal.Equals(retObject.SocketAddress))
     {
         try
         {
             remoteEP = point2.Create(retObject.SocketAddress);
         }
         catch
         {
         }
     }
     if (s_LoggingEnabled)
     {
         Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", retObject);
     }
     return retObject;
 }