private StartOperationCommon ( Socket socket ) : void | ||
socket | Socket | |
Résultat | void |
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e) { bool retval; // Throw if multiple buffers specified. if (e.m_BufferList != null) { throw new ArgumentException(SR.GetString(SR.net_multibuffernotsupported), "BufferList"); } // Throw if RemoteEndPoint is null. if (e.RemoteEndPoint == null) { throw new ArgumentNullException("remoteEP"); } EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint; if (dnsEP != null) { Socket attemptSocket = null; MultipleConnectAsync multipleConnectAsync = null; if (dnsEP.AddressFamily == AddressFamily.Unspecified) { multipleConnectAsync = new MultipleSocketMultipleConnectAsync(socketType, protocolType); } else { attemptSocket = new Socket(dnsEP.AddressFamily, socketType, protocolType); multipleConnectAsync = new SingleSocketMultipleConnectAsync(attemptSocket, false); } e.StartOperationCommon(attemptSocket); e.StartOperationWrapperConnect(multipleConnectAsync); retval = multipleConnectAsync.StartConnectAsync(e, dnsEP); } else { Socket attemptSocket = new Socket(endPointSnapshot.AddressFamily, socketType, protocolType); retval = attemptSocket.ConnectAsync(e); } return(retval); }
public bool SendPacketsAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "SendPacketsAsync", ""); } // Throw if socket disposed if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } if (e.SendPacketsElements == null) { throw new ArgumentNullException("e.SendPacketsElements"); } if (!Connected) { throw new NotSupportedException(SR.net_notconnected); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationSendPackets(); // Make the native call. SocketError socketError; Debug.Assert(e.SendPacketsDescriptorCount != null); if (e.SendPacketsDescriptorCount > 0) { try { socketError = e.DoOperationSendPackets(this, _handle); } catch (Exception) { // Clear in-use flag on event args object. e.Complete(); throw; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); retval = false; } else { retval = true; } } else { // No buffers or files to send. e.FinishOperationSuccess(SocketError.Success, 0, SocketFlags.None); retval = false; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "SendPacketsAsync", retval); } return retval; }
public bool ReceiveAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "ReceiveAsync", ""); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationReceive(); // Local vars for sync completion of native call. SocketFlags flags; int bytesTransferred; SocketError socketError; // Wrap native methods with try/catch so event args object can be cleaned up. try { socketError = e.DoOperationReceive(_handle, out flags, out bytesTransferred); } catch (Exception ex) { // Clear in-use flag on event args object. e.Complete(); throw ex; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, flags); retval = false; } else { retval = true; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "ReceiveAsync", retval); } return retval; }
public bool ConnectAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "ConnectAsync", ""); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } if (e._bufferList != null) { throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("remoteEP"); } if (_isListening) { throw new InvalidOperationException(SR.net_sockets_mustnotlisten); } // Check permissions for connect and prepare SocketAddress. EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint; if (dnsEP != null) { if (s_loggingEnabled) { Logging.PrintInfo(Logging.Sockets, "Socket#" + Logging.HashString(this) + "::ConnectAsync " + SR.net_log_socket_connect_dnsendpoint); } if (dnsEP.AddressFamily != AddressFamily.Unspecified && !CanTryAddressFamily(dnsEP.AddressFamily)) { throw new NotSupportedException(SR.net_invalidversion); } MultipleConnectAsync multipleConnectAsync = new SingleSocketMultipleConnectAsync(this, true); e.StartOperationCommon(this); e.StartOperationWrapperConnect(multipleConnectAsync); retval = multipleConnectAsync.StartConnectAsync(e, dnsEP); } else { // Throw if remote address family doesn't match socket. if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { throw new NotSupportedException(SR.net_invalidversion); } e._socketAddress = CheckCacheRemote(ref endPointSnapshot, false); // Do wildcard bind if socket not bound. if (_rightEndPoint == null) { if (endPointSnapshot.AddressFamily == AddressFamily.InterNetwork) { InternalBind(new IPEndPoint(IPAddress.Any, 0)); } else { InternalBind(new IPEndPoint(IPAddress.IPv6Any, 0)); } } // Save the old RightEndPoint and prep new RightEndPoint. EndPoint oldEndPoint = _rightEndPoint; if (_rightEndPoint == null) { _rightEndPoint = endPointSnapshot; } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationConnect(); // Make the native call. int bytesTransferred; SocketError socketError = SocketError.Success; try { socketError = e.DoOperationConnect(this, _handle, out bytesTransferred); } catch (Exception ex) { _rightEndPoint = oldEndPoint; // Clear in-use flag on event args object. e.Complete(); throw ex; } // Handle failure where completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "ConnectAsync", retval); } return retval; }
// // SendToAsync // public bool SendToAsync(SocketAsyncEventArgs e) { bool retval; if(s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "SendToAsync", ""); // Throw if socket disposed if(CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Throw if remote endpoint property is null. if(e.RemoteEndPoint == null) { throw new ArgumentNullException("RemoteEndPoint"); } // Check permissions for connect and prepare SocketAddress EndPoint endPointSnapshot = e.RemoteEndPoint; e.m_SocketAddress = CheckCacheRemote(ref endPointSnapshot, false); // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationSendTo(); BindToCompletionPort(); // Make the native call. int bytesTransferred; SocketError socketError; // Wrap native methods with try/catch so event args object can be cleaned up try { if(e.m_Buffer != null) { // Single buffer case socketError = UnsafeNclNativeMethods.OSSOCK.WSASendTo( m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero); } else { socketError = UnsafeNclNativeMethods.OSSOCK.WSASendTo( m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero); } } catch(Exception ex) { // clear in-use on event arg object e.Complete(); throw ex; } // Native method emits single catch-all error code when error occurs. // Must get Win32 error for specific error code. if(socketError != SocketError.Success) { socketError = (SocketError)Marshal.GetLastWin32Error(); } // Handle completion when completion port is not posted. if(socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if(s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "SendToAsync", retval); return retval; }
// // ReceiveMessageFromAsync // public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) { bool retval; if(s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "ReceiveMessageFromAsync", ""); // Throw if socket disposed if(CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Throw if remote endpoint property is null. if(e.RemoteEndPoint == null) { throw new ArgumentNullException("RemoteEndPoint"); } if(!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { throw new ArgumentException(SR.GetString(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, addressFamily), "RemoteEndPoint"); } // 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 EndPoint endPointSnapshot = e.RemoteEndPoint; e.m_SocketAddress = SnapshotAndSerialize(ref endPointSnapshot); // DualMode may have updated the endPointSnapshot, and it has to have the same AddressFamily as // e.m_SocketAddres for Create to work later. e.RemoteEndPoint = endPointSnapshot; SetReceivingPacketInformation(); // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationReceiveMessageFrom(); BindToCompletionPort(); // Make the native call. int bytesTransferred; SocketError socketError; try { socketError = WSARecvMsg( m_Handle, e.m_PtrWSAMessageBuffer, out bytesTransferred, e.m_PtrNativeOverlapped, IntPtr.Zero); } catch(Exception ex) { // clear in-use on event arg object e.Complete(); throw ex; } // Native method emits single catch-all error code when error occurs. // Must get Win32 error for specific error code. if(socketError != SocketError.Success) { socketError = (SocketError)Marshal.GetLastWin32Error(); } // Handle completion when completion port is not posted. if(socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if(s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "ReceiveMessageFromAsync", retval); return retval; }
// // DisconnectAsync // public bool DisconnectAsync(SocketAsyncEventArgs e) { bool retval; if(s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "DisconnectAsync", ""); // Throw if socket disposed if(CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationDisconnect(); BindToCompletionPort(); // Make the native call. SocketError socketError = SocketError.Success; try { if(!DisconnectEx( m_Handle, e.m_PtrNativeOverlapped, (int)(e.DisconnectReuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0)) { socketError = (SocketError)Marshal.GetLastWin32Error(); } } catch(Exception ex) { // clear in-use on event arg object e.Complete(); throw ex; } // Handle completion when completion port is not posted. if(socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); retval = false; } else { retval = true; } if(s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "DisconnectAsync", retval); return retval; }
// // AcceptAsync // public bool AcceptAsync(SocketAsyncEventArgs e) { bool retval; if(s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "AcceptAsync", ""); // Throw if socket disposed if(CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Throw if multiple buffers specified. if(e.m_BufferList != null) { throw new ArgumentException(SR.GetString(SR.net_multibuffernotsupported), "BufferList"); } // Throw if not bound. if(m_RightEndPoint == null) { throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustbind)); } // Throw if not listening. if(!isListening) { throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustlisten)); } // Handle AcceptSocket property. if(e.AcceptSocket == null) { // Accept socket not specified - create it. e.AcceptSocket = new Socket(addressFamily, socketType, protocolType); } else { // Validate accept socket for use here. if(e.AcceptSocket.m_RightEndPoint != null && !e.AcceptSocket.m_IsDisconnected) { throw new InvalidOperationException(SR.GetString(SR.net_sockets_namedmustnotbebound, "AcceptSocket")); } } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationAccept(); BindToCompletionPort(); // Local variables for [....] completion. int bytesTransferred; SocketError socketError = SocketError.Success; // Make the native call. try { if(!AcceptEx( m_Handle, e.AcceptSocket.m_Handle, (e.m_PtrSingleBuffer != IntPtr.Zero) ? e.m_PtrSingleBuffer : e.m_PtrAcceptBuffer, (e.m_PtrSingleBuffer != IntPtr.Zero) ? e.Count - e.m_AcceptAddressBufferCount : 0, e.m_AcceptAddressBufferCount / 2, e.m_AcceptAddressBufferCount / 2, out bytesTransferred, e.m_PtrNativeOverlapped)) { socketError = (SocketError)Marshal.GetLastWin32Error(); } } catch (Exception ex) { // clear in-use on event arg object e.Complete(); throw ex; } // Handle completion when completion port is not posted. if(socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if(s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "AcceptAsync", retval); return retval; }
public bool SendAsync(SocketAsyncEventArgs e) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, e); bool retval; if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException(nameof(e)); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationSend(); // Local vars for sync completion of native call. int bytesTransferred; SocketError socketError; // Wrap native methods with try/catch so event args object can be cleaned up. try { socketError = e.DoOperationSend(_handle, out bytesTransferred); } catch { // Clear in-use flag on event args object. e.Complete(); throw; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval); return retval; }
public bool DisconnectAsync(SocketAsyncEventArgs e) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); bool retval; // Throw if socket disposed if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationDisconnect(); SocketError socketError = SocketError.Success; try { socketError = e.DoOperationDisconnect(this, _handle); } catch { // clear in-use on event arg object e.Complete(); throw; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); retval = false; } else { retval = true; } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, retval); return retval; }
public bool SendToAsync(SocketAsyncEventArgs e) { bool flag; int num; SocketError error; if (s_LoggingEnabled) { Logging.Enter(Logging.Sockets, this, "SendToAsync", ""); } if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("RemoteEndPoint"); } EndPoint remoteEndPoint = e.RemoteEndPoint; e.m_SocketAddress = this.CheckCacheRemote(ref remoteEndPoint, false); e.StartOperationCommon(this); e.StartOperationSendTo(); this.BindToCompletionPort(); try { if (e.m_Buffer != null) { error = UnsafeNclNativeMethods.OSSOCK.WSASendTo(this.m_Handle, ref e.m_WSABuffer, 1, out num, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero); } else { error = UnsafeNclNativeMethods.OSSOCK.WSASendTo(this.m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out num, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero); } } catch (Exception exception) { e.Complete(); throw exception; } if (error != SocketError.Success) { error = (SocketError) Marshal.GetLastWin32Error(); } if ((error != SocketError.Success) && (error != SocketError.IOPending)) { e.FinishOperationSyncFailure(error, num, SocketFlags.None); flag = false; } else { flag = true; } if (s_LoggingEnabled) { Logging.Exit(Logging.Sockets, this, "SendToAsync", flag); } return flag; }
public bool SendPacketsAsync(SocketAsyncEventArgs e) { bool flag; SocketError success; bool flag2; if (s_LoggingEnabled) { Logging.Enter(Logging.Sockets, this, "SendPacketsAsync", ""); } if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } if (!this.Connected) { throw new NotSupportedException(SR.GetString("net_notconnected")); } e.StartOperationCommon(this); e.StartOperationSendPackets(); this.BindToCompletionPort(); try { flag2 = this.TransmitPackets(this.m_Handle, e.m_PtrSendPacketsDescriptor, e.m_SendPacketsElements.Length, e.m_SendPacketsSendSize, e.m_PtrNativeOverlapped, e.m_SendPacketsFlags); } catch (Exception exception) { e.Complete(); throw exception; } if (!flag2) { success = (SocketError) Marshal.GetLastWin32Error(); } else { success = SocketError.Success; } if ((success != SocketError.Success) && (success != SocketError.IOPending)) { e.FinishOperationSyncFailure(success, 0, SocketFlags.None); flag = false; } else { flag = true; } if (s_LoggingEnabled) { Logging.Exit(Logging.Sockets, this, "SendPacketsAsync", flag); } return flag; }
public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) { bool flag; int num; SocketError error; if (s_LoggingEnabled) { Logging.Enter(Logging.Sockets, this, "ReceiveMessageFromAsync", ""); } if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("RemoteEndPoint"); } if (e.RemoteEndPoint.AddressFamily != this.addressFamily) { throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", new object[] { e.RemoteEndPoint.AddressFamily, this.addressFamily }), "RemoteEndPoint"); } EndPoint remoteEndPoint = e.RemoteEndPoint; e.m_SocketAddress = this.SnapshotAndSerialize(ref remoteEndPoint); this.SetReceivingPacketInformation(); e.StartOperationCommon(this); e.StartOperationReceiveMessageFrom(); this.BindToCompletionPort(); try { error = this.WSARecvMsg(this.m_Handle, e.m_PtrWSAMessageBuffer, out num, e.m_PtrNativeOverlapped, IntPtr.Zero); } catch (Exception exception) { e.Complete(); throw exception; } if (error != SocketError.Success) { error = (SocketError) Marshal.GetLastWin32Error(); } if ((error != SocketError.Success) && (error != SocketError.IOPending)) { e.FinishOperationSyncFailure(error, num, SocketFlags.None); flag = false; } else { flag = true; } if (s_LoggingEnabled) { Logging.Exit(Logging.Sockets, this, "ReceiveMessageFromAsync", flag); } return flag; }
public bool ReceiveAsync(SocketAsyncEventArgs e) { bool flag; int num; SocketError error; if (s_LoggingEnabled) { Logging.Enter(Logging.Sockets, this, "ReceiveAsync", ""); } if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } e.StartOperationCommon(this); e.StartOperationReceive(); this.BindToCompletionPort(); SocketFlags socketFlags = e.m_SocketFlags; try { if (e.m_Buffer != null) { error = UnsafeNclNativeMethods.OSSOCK.WSARecv(this.m_Handle, ref e.m_WSABuffer, 1, out num, ref socketFlags, e.m_PtrNativeOverlapped, IntPtr.Zero); } else { error = UnsafeNclNativeMethods.OSSOCK.WSARecv(this.m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out num, ref socketFlags, e.m_PtrNativeOverlapped, IntPtr.Zero); } } catch (Exception exception) { e.Complete(); throw exception; } if (error != SocketError.Success) { error = (SocketError) Marshal.GetLastWin32Error(); } if ((error != SocketError.Success) && (error != SocketError.IOPending)) { e.FinishOperationSyncFailure(error, num, socketFlags); flag = false; } else { flag = true; } if (s_LoggingEnabled) { Logging.Exit(Logging.Sockets, this, "ReceiveAsync", flag); } return flag; }
/// <summary> /// Begins an asynchronous operation to accept an incoming connection attempt. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation.Returns false if the I/O operation completed synchronously. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.ArgumentException">An argument is not valid. This exception occurs if the buffer provided is not large enough. The buffer must be at least 2 * (sizeof(SOCKADDR_STORAGE + 16) bytes. This exception also occurs if multiple buffers are specified, the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.BufferList"/> property is not null.</exception><exception cref="T:System.ArgumentOutOfRangeException">An argument is out of range. The exception occurs if the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.Count"/> is less than 0.</exception><exception cref="T:System.InvalidOperationException">An invalid operation was requested. This exception occurs if the accepting <see cref="T:System.Net.Sockets.Socket"/> is not listening for connections or the accepted socket is bound. You must call the <see cref="M:System.Net.Sockets.Socket.Bind(System.Net.EndPoint)"/> and <see cref="M:System.Net.Sockets.Socket.Listen(System.Int32)"/> method before calling the <see cref="M:System.Net.Sockets.Socket.AcceptAsync(System.Net.Sockets.SocketAsyncEventArgs)"/> method.This exception also occurs if the socket is already connected or a socket operation was already in progress using the specified <paramref name="e"/> parameter. </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.NotSupportedException">Windows XP or later is required for this method.</exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception> public bool AcceptAsync(SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "AcceptAsync", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (e.m_BufferList != null) throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList"); if (this.m_RightEndPoint == null) throw new InvalidOperationException(SR.GetString("net_sockets_mustbind")); if (!this.isListening) throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten")); if (e.AcceptSocket == null) e.AcceptSocket = new Socket(this.addressFamily, this.socketType, this.protocolType); else if (e.AcceptSocket.m_RightEndPoint != null && !e.AcceptSocket.m_IsDisconnected) throw new InvalidOperationException(SR.GetString("net_sockets_namedmustnotbebound", new object[1] { (object) "AcceptSocket" })); e.StartOperationCommon(this); e.StartOperationAccept(); this.BindToCompletionPort(); SocketError socketError = SocketError.Success; int bytesReceived; try { if (!this.AcceptEx(this.m_Handle, e.AcceptSocket.m_Handle, e.m_PtrSingleBuffer != IntPtr.Zero ? e.m_PtrSingleBuffer : e.m_PtrAcceptBuffer, e.m_PtrSingleBuffer != IntPtr.Zero ? e.Count - e.m_AcceptAddressBufferCount : 0, e.m_AcceptAddressBufferCount / 2, e.m_AcceptAddressBufferCount / 2, out bytesReceived, (SafeHandle) e.m_PtrNativeOverlapped)) socketError = (SocketError) Marshal.GetLastWin32Error(); } catch (Exception ex) { e.Complete(); throw ex; } bool flag; if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesReceived, SocketFlags.None); flag = false; } else flag = true; if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "AcceptAsync", (object) (bool) (flag ? 1 : 0)); return flag; }
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { NetEventSource.Enter(NetEventSource.ComponentType.Socket, null, nameof(ConnectAsync), ""); } if (e == null) { throw new ArgumentNullException(nameof(e)); } if (e._bufferList != null) { throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("remoteEP"); } EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint; if (dnsEP != null) { Socket attemptSocket = null; MultipleConnectAsync multipleConnectAsync = null; if (dnsEP.AddressFamily == AddressFamily.Unspecified) { // Disable CS0162 and CS0429: Unreachable code detected // // SuportsMultipleConnectAttempts is a constant; when false, the following lines will trigger CS0162 or CS0429. // // This is the only *Connect* API that actually supports multiple endpoint attempts, as it's responsible // for creating each Socket instance and can create one per attempt (with the instance methods, once a // connect fails, on unix systems that socket can't be used for subsequent connect attempts). #pragma warning disable 162, 429 multipleConnectAsync = SocketPal.SupportsMultipleConnectAttempts ? (MultipleConnectAsync)(new DualSocketMultipleConnectAsync(socketType, protocolType)) : (MultipleConnectAsync)(new MultipleSocketMultipleConnectAsync(socketType, protocolType)); #pragma warning restore } else { attemptSocket = new Socket(dnsEP.AddressFamily, socketType, protocolType); multipleConnectAsync = new SingleSocketMultipleConnectAsync(attemptSocket, false); } e.StartOperationCommon(attemptSocket); e.StartOperationWrapperConnect(multipleConnectAsync); retval = multipleConnectAsync.StartConnectAsync(e, dnsEP); } else { Socket attemptSocket = new Socket(endPointSnapshot.AddressFamily, socketType, protocolType); retval = attemptSocket.ConnectAsync(e); } if (s_loggingEnabled) { NetEventSource.Exit(NetEventSource.ComponentType.Socket, null, nameof(ConnectAsync), retval); } return retval; }
/// <summary> /// Begins an asynchronous request for a connection to a remote host. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.ArgumentException">An argument is not valid. This exception occurs if multiple buffers are specified, the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.BufferList"/> property is not null. </exception><exception cref="T:System.ArgumentNullException">The <paramref name="e"/> parameter cannot be null and the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.RemoteEndPoint"/> cannot be null.</exception><exception cref="T:System.InvalidOperationException">The <see cref="T:System.Net.Sockets.Socket"/> is listening or a socket operation was already in progress using the <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object specified in the <paramref name="e"/> parameter.</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.NotSupportedException">Windows XP or later is required for this method. This exception also occurs if the local endpoint and the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.RemoteEndPoint"/> are not the same address family.</exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.Security.SecurityException">A caller higher in the call stack does not have permission for the requested operation.</exception> public bool ConnectAsync(SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "ConnectAsync", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (e.m_BufferList != null) throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList"); if (e.RemoteEndPoint == null) throw new ArgumentNullException("remoteEP"); if (this.isListening) throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten")); EndPoint remoteEndPoint = e.RemoteEndPoint; DnsEndPoint endPoint1 = remoteEndPoint as DnsEndPoint; bool flag; if (endPoint1 != null) { if (Socket.s_LoggingEnabled) Logging.PrintInfo(Logging.Sockets, "Socket#" + ValidationHelper.HashString((object) this) + "::ConnectAsync " + SR.GetString("net_log_socket_connect_dnsendpoint")); if (endPoint1.AddressFamily != AddressFamily.Unspecified && !this.CanTryAddressFamily(endPoint1.AddressFamily)) throw new NotSupportedException(SR.GetString("net_invalidversion")); MultipleConnectAsync args = (MultipleConnectAsync) new SingleSocketMultipleConnectAsync(this, true); e.StartOperationCommon(this); e.StartOperationWrapperConnect(args); flag = args.StartConnectAsync(e, endPoint1); } else { if (!this.CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) throw new NotSupportedException(SR.GetString("net_invalidversion")); e.m_SocketAddress = this.CheckCacheRemote(ref remoteEndPoint, false); if (this.m_RightEndPoint == null) { if (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork) this.InternalBind((EndPoint) new IPEndPoint(IPAddress.Any, 0)); else this.InternalBind((EndPoint) new IPEndPoint(IPAddress.IPv6Any, 0)); } EndPoint endPoint2 = this.m_RightEndPoint; if (this.m_RightEndPoint == null) this.m_RightEndPoint = remoteEndPoint; e.StartOperationCommon(this); e.StartOperationConnect(); this.BindToCompletionPort(); SocketError socketError = SocketError.Success; int bytesSent; try { if (!this.ConnectEx(this.m_Handle, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrSingleBuffer, e.Count, out bytesSent, (SafeHandle) e.m_PtrNativeOverlapped)) socketError = (SocketError) Marshal.GetLastWin32Error(); } catch (Exception ex) { this.m_RightEndPoint = endPoint2; e.Complete(); throw ex; } if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesSent, SocketFlags.None); flag = false; } else flag = true; } if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "ConnectAsync", (object) (bool) (flag ? 1 : 0)); return flag; }
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e) { bool retval; if (s_LoggingEnabled) Logging.Enter(Logging.Sockets, null, "ConnectAsync", ""); // Throw if multiple buffers specified. if (e.m_BufferList != null) { throw new ArgumentException(SR.GetString(SR.net_multibuffernotsupported), "BufferList"); } // Throw if RemoteEndPoint is null. if (e.RemoteEndPoint == null) { throw new ArgumentNullException("remoteEP"); } EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint; if (dnsEP != null) { Socket attemptSocket = null; MultipleConnectAsync multipleConnectAsync = null; if (dnsEP.AddressFamily == AddressFamily.Unspecified) { multipleConnectAsync = new MultipleSocketMultipleConnectAsync(socketType, protocolType); } else { attemptSocket = new Socket(dnsEP.AddressFamily, socketType, protocolType); multipleConnectAsync = new SingleSocketMultipleConnectAsync(attemptSocket, false); } e.StartOperationCommon(attemptSocket); e.StartOperationWrapperConnect(multipleConnectAsync); retval = multipleConnectAsync.StartConnectAsync(e, dnsEP); } else { Socket attemptSocket = new Socket(endPointSnapshot.AddressFamily, socketType, protocolType); retval = attemptSocket.ConnectAsync(e); } if (s_LoggingEnabled) Logging.Exit(Logging.Sockets, null, "ConnectAsync", retval); return retval; }
/// <summary> /// Begins an asynchronous request to disconnect from a remote endpoint. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.ArgumentNullException">The <paramref name="e"/> parameter cannot be null.</exception><exception cref="T:System.InvalidOperationException">A socket operation was already in progress using the <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object specified in the <paramref name="e"/> parameter.</exception><exception cref="T:System.NotSupportedException">Windows XP or later is required for this method.</exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.Net.Sockets.SocketException">An error occurred when attempting to access the socket. </exception> public bool DisconnectAsync(SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "DisconnectAsync", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); e.StartOperationCommon(this); e.StartOperationDisconnect(); this.BindToCompletionPort(); SocketError socketError = SocketError.Success; try { if (!this.DisconnectEx(this.m_Handle, (SafeHandle) e.m_PtrNativeOverlapped, e.DisconnectReuseSocket ? 2 : 0, 0)) socketError = (SocketError) Marshal.GetLastWin32Error(); } catch (Exception ex) { e.Complete(); throw ex; } bool flag; if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); flag = false; } else flag = true; if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "DisconnectAsync", (object) (bool) (flag ? 1 : 0)); return flag; }
// // ReceiveAsync // public bool ReceiveAsync(SocketAsyncEventArgs e) { bool retval; if(s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "ReceiveAsync", ""); // Throw if socket disposed if(CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationReceive(); BindToCompletionPort(); // Local vars for [....] completion of native call. SocketFlags flags = e.m_SocketFlags; int bytesTransferred; SocketError socketError; // Wrap native methods with try/catch so event args object can be cleaned up try { if(e.m_Buffer != null) { // Single buffer case socketError = UnsafeNclNativeMethods.OSSOCK.WSARecv( m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, ref flags, e.m_PtrNativeOverlapped, IntPtr.Zero); } else { // Multi buffer case socketError = UnsafeNclNativeMethods.OSSOCK.WSARecv( m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, ref flags, e.m_PtrNativeOverlapped, IntPtr.Zero); } } catch(Exception ex) { // clear in-use on event arg object e.Complete(); throw ex; } // Native method emits single catch-all error code when error occurs. // Must get Win32 error for specific error code. if(socketError != SocketError.Success) { socketError = (SocketError)Marshal.GetLastWin32Error(); } // Handle completion when completion port is not posted. if(socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, flags); retval = false; } else { retval = true; } if(s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "ReceiveAsync", retval); return retval; }
/// <summary> /// Begins to asynchronously receive the specified number of bytes of data into the specified location in the data buffer, using the specified <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.SocketFlags"/>, and stores the endpoint and packet information. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.ArgumentNullException">The <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.RemoteEndPoint"/> cannot be null.</exception><exception cref="T:System.NotSupportedException">Windows XP or later is required for this method.</exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.Net.Sockets.SocketException">An error occurred when attempting to access the socket. </exception> public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "ReceiveMessageFromAsync", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (e.RemoteEndPoint == null) throw new ArgumentNullException("RemoteEndPoint"); if (!this.CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", (object) e.RemoteEndPoint.AddressFamily, (object) this.addressFamily), "RemoteEndPoint"); } else { EndPoint remoteEndPoint = e.RemoteEndPoint; e.m_SocketAddress = this.SnapshotAndSerialize(ref remoteEndPoint); e.RemoteEndPoint = remoteEndPoint; this.SetReceivingPacketInformation(); e.StartOperationCommon(this); e.StartOperationReceiveMessageFrom(); this.BindToCompletionPort(); int bytesTransferred; SocketError socketError; try { socketError = this.WSARecvMsg(this.m_Handle, e.m_PtrWSAMessageBuffer, out bytesTransferred, (SafeHandle) e.m_PtrNativeOverlapped, IntPtr.Zero); } catch (Exception ex) { e.Complete(); throw ex; } if (socketError != SocketError.Success) socketError = (SocketError) Marshal.GetLastWin32Error(); bool flag; if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); flag = false; } else flag = true; if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "ReceiveMessageFromAsync", (object) (bool) (flag ? 1 : 0)); return flag; } }
// // SendPacketsAsync // public bool SendPacketsAsync(SocketAsyncEventArgs e) { bool retval; if(s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "SendPacketsAsync", ""); // Throw if socket disposed if(CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } // Throw if not connected. if(!Connected) { throw new NotSupportedException(SR.GetString(SR.net_notconnected)); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationSendPackets(); BindToCompletionPort(); // Make the native call. SocketError socketError; bool result; if (e.m_SendPacketsDescriptor.Length > 0) { try { result = TransmitPackets( m_Handle, e.m_PtrSendPacketsDescriptor, e.m_SendPacketsDescriptor.Length, e.m_SendPacketsSendSize, e.m_PtrNativeOverlapped, e.m_SendPacketsFlags); } catch(Exception) { // clear in-use on event arg object e.Complete(); throw; } if(!result) { socketError = (SocketError)Marshal.GetLastWin32Error(); } else { socketError = SocketError.Success; } // Handle completion when completion port is not posted. if(socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); retval = false; } else { retval = true; } } else { // No buffers or files to send. e.FinishOperationSuccess(SocketError.Success, 0, SocketFlags.None); retval = false; } if(s_LoggingEnabled) Logging.Exit(Logging.Sockets, this, "SendPacketsAsync", retval); return retval; }
/// <summary> /// Sends a collection of files or in memory data buffers asynchronously to a connected <see cref="T:System.Net.Sockets.Socket"/> object. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.IO.FileNotFoundException">The file specified in the <see cref="P:System.Net.Sockets.SendPacketsElement.FilePath"/> property was not found. </exception><exception cref="T:System.InvalidOperationException">A socket operation was already in progress using the <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object specified in the <paramref name="e"/> parameter.</exception><exception cref="T:System.NotSupportedException">Windows XP or later is required for this method. This exception also occurs if the <see cref="T:System.Net.Sockets.Socket"/> is not connected to a remote host. </exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.Net.Sockets.SocketException">A connectionless <see cref="T:System.Net.Sockets.Socket"/> is being used and the file being sent exceeds the maximum packet size of the underlying transport.</exception> public bool SendPacketsAsync(SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "SendPacketsAsync", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (!this.Connected) throw new NotSupportedException(SR.GetString("net_notconnected")); e.StartOperationCommon(this); e.StartOperationSendPackets(); this.BindToCompletionPort(); bool flag1; if (e.m_SendPacketsDescriptor.Length > 0) { bool flag2; try { flag2 = this.TransmitPackets(this.m_Handle, e.m_PtrSendPacketsDescriptor, e.m_SendPacketsDescriptor.Length, e.m_SendPacketsSendSize, e.m_PtrNativeOverlapped, e.m_SendPacketsFlags); } catch (Exception ex) { e.Complete(); throw; } SocketError socketError = flag2 ? SocketError.Success : (SocketError) Marshal.GetLastWin32Error(); if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); flag1 = false; } else flag1 = true; } else { e.FinishOperationSuccess(SocketError.Success, 0, SocketFlags.None); flag1 = false; } if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "SendPacketsAsync", (object) (bool) (flag1 ? 1 : 0)); return flag1; }
public bool AcceptAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "AcceptAsync", ""); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } if (e._bufferList != null) { throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); } if (_rightEndPoint == null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } if (!_isListening) { throw new InvalidOperationException(SR.net_sockets_mustlisten); } // Handle AcceptSocket property. SafeCloseSocket acceptHandle; e.AcceptSocket = GetOrCreateAcceptSocket(e.AcceptSocket, true, "AcceptSocket", out acceptHandle); // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationAccept(); // Local variables for sync completion. int bytesTransferred; SocketError socketError = SocketError.Success; // Make the native call. try { socketError = e.DoOperationAccept(this, _handle, acceptHandle, out bytesTransferred); } catch (Exception ex) { // Clear in-use flag on event args object. e.Complete(); throw ex; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "AcceptAsync", retval); } return retval; }
/// <summary> /// Sends data asynchronously to a specific remote host. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.ArgumentNullException">The <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.RemoteEndPoint"/> cannot be null.</exception><exception cref="T:System.InvalidOperationException">A socket operation was already in progress using the <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object specified in the <paramref name="e"/> parameter.</exception><exception cref="T:System.NotSupportedException">Windows XP or later is required for this method.</exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.Net.Sockets.SocketException">The protocol specified is connection-oriented, but the <see cref="T:System.Net.Sockets.Socket"/> is not yet connected.</exception> public bool SendToAsync(SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "SendToAsync", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (e.RemoteEndPoint == null) throw new ArgumentNullException("RemoteEndPoint"); EndPoint remoteEndPoint = e.RemoteEndPoint; e.m_SocketAddress = this.CheckCacheRemote(ref remoteEndPoint, false); e.StartOperationCommon(this); e.StartOperationSendTo(); this.BindToCompletionPort(); int bytesTransferred; SocketError socketError; try { socketError = e.m_Buffer == null ? UnsafeNclNativeMethods.OSSOCK.WSASendTo(this.m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero) : UnsafeNclNativeMethods.OSSOCK.WSASendTo(this.m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, (SafeHandle) e.m_PtrNativeOverlapped, IntPtr.Zero); } catch (Exception ex) { e.Complete(); throw ex; } if (socketError != SocketError.Success) socketError = (SocketError) Marshal.GetLastWin32Error(); bool flag; if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); flag = false; } else flag = true; if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "SendToAsync", (object) (bool) (flag ? 1 : 0)); return flag; }
public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, null, "ConnectAsync", ""); } if (e == null) { throw new ArgumentNullException("e"); } if (e._bufferList != null) { throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("remoteEP"); } EndPoint endPointSnapshot = e.RemoteEndPoint; DnsEndPoint dnsEP = endPointSnapshot as DnsEndPoint; if (dnsEP != null) { Socket attemptSocket = null; MultipleConnectAsync multipleConnectAsync = null; if (dnsEP.AddressFamily == AddressFamily.Unspecified) { // Disable CS0162 and CS0429: Unreachable code detected // // SuportsMultipleConnectAttempts is a constant; when false, the following lines will trigger CS0162 or CS0429. #pragma warning disable 162, 429 multipleConnectAsync = SocketPal.SupportsMultipleConnectAttempts ? (MultipleConnectAsync)(new DualSocketMultipleConnectAsync(socketType, protocolType)) : (MultipleConnectAsync)(new MultipleSocketMultipleConnectAsync(socketType, protocolType)); #pragma warning restore } else { attemptSocket = new Socket(dnsEP.AddressFamily, socketType, protocolType); multipleConnectAsync = new SingleSocketMultipleConnectAsync(attemptSocket, false); } e.StartOperationCommon(attemptSocket); e.StartOperationWrapperConnect(multipleConnectAsync); retval = multipleConnectAsync.StartConnectAsync(e, dnsEP); } else { Socket attemptSocket = new Socket(endPointSnapshot.AddressFamily, socketType, protocolType); retval = attemptSocket.ConnectAsync(e); } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, null, "ConnectAsync", retval); } return retval; }
/// <summary> /// Begins an asynchronous request for a connection to a remote host. /// </summary> /// /// <returns> /// Returns true if the I/O operation is pending. The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will be raised upon completion of the operation. Returns false if the I/O operation completed synchronously. In this case, The <see cref="E:System.Net.Sockets.SocketAsyncEventArgs.Completed"/> event on the <paramref name="e"/> parameter will not be raised and the <paramref name="e"/> object passed as a parameter may be examined immediately after the method call returns to retrieve the result of the operation. /// </returns> /// <param name="socketType">One of the <see cref="T:System.Net.Sockets.SocketType"/> values.</param><param name="protocolType">One of the <see cref="T:System.Net.Sockets.ProtocolType"/> values.</param><param name="e">The <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object to use for this asynchronous socket operation.</param><exception cref="T:System.ArgumentException">An argument is not valid. This exception occurs if multiple buffers are specified, the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.BufferList"/> property is not null. </exception><exception cref="T:System.ArgumentNullException">The <paramref name="e"/> parameter cannot be null and the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.RemoteEndPoint"/> cannot be null.</exception><exception cref="T:System.InvalidOperationException">The <see cref="T:System.Net.Sockets.Socket"/> is listening or a socket operation was already in progress using the <see cref="T:System.Net.Sockets.SocketAsyncEventArgs"/> object specified in the <paramref name="e"/> parameter.</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.NotSupportedException">Windows XP or later is required for this method. This exception also occurs if the local endpoint and the <see cref="P:System.Net.Sockets.SocketAsyncEventArgs.RemoteEndPoint"/> are not the same address family.</exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.Security.SecurityException">A caller higher in the call stack does not have permission for the requested operation.</exception> public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (string) null, "ConnectAsync", ""); if (e.m_BufferList != null) throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList"); if (e.RemoteEndPoint == null) throw new ArgumentNullException("remoteEP"); EndPoint remoteEndPoint = e.RemoteEndPoint; DnsEndPoint endPoint = remoteEndPoint as DnsEndPoint; bool flag; if (endPoint != null) { Socket socket = (Socket) null; MultipleConnectAsync args; if (endPoint.AddressFamily == AddressFamily.Unspecified) { args = (MultipleConnectAsync) new MultipleSocketMultipleConnectAsync(socketType, protocolType); } else { socket = new Socket(endPoint.AddressFamily, socketType, protocolType); args = (MultipleConnectAsync) new SingleSocketMultipleConnectAsync(socket, false); } e.StartOperationCommon(socket); e.StartOperationWrapperConnect(args); flag = args.StartConnectAsync(e, endPoint); } else flag = new Socket(remoteEndPoint.AddressFamily, socketType, protocolType).ConnectAsync(e); if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (string) null, "ConnectAsync", (object) (bool) (flag ? 1 : 0)); return flag; }
public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "ReceiveMessageFromAsync", ""); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("RemoteEndPoint"); } if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint"); } // 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. EndPoint endPointSnapshot = e.RemoteEndPoint; e._socketAddress = SnapshotAndSerialize(ref endPointSnapshot); // DualMode may have updated the endPointSnapshot, and it has to have the same AddressFamily as // e.m_SocketAddres for Create to work later. e.RemoteEndPoint = endPointSnapshot; SetReceivingPacketInformation(); // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationReceiveMessageFrom(); // Make the native call. int bytesTransferred; SocketError socketError; try { socketError = e.DoOperationReceiveMessageFrom(this, _handle, out bytesTransferred); } catch (Exception ex) { // Clear in-use flag on event args object. e.Complete(); throw ex; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "ReceiveMessageFromAsync", retval); } return retval; }
public bool DisconnectAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "DisconnectAsync", ""); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationDisconnect(); // Make the native call. SocketError socketError = SocketError.Success; try { socketError = e.DoOperationDisconnect(this, _handle); } catch (Exception ex) { // Clear in-use flag on event args object. e.Complete(); throw ex; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None); retval = false; } else { retval = true; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "DisconnectAsync", retval); } return retval; }
public bool SendToAsync(SocketAsyncEventArgs e) { bool retval; if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "SendToAsync", ""); } if (CleanedUp) { throw new ObjectDisposedException(GetType().FullName); } if (e == null) { throw new ArgumentNullException("e"); } if (e.RemoteEndPoint == null) { throw new ArgumentNullException("RemoteEndPoint"); } // Check permissions for connect and prepare SocketAddress EndPoint endPointSnapshot = e.RemoteEndPoint; e._socketAddress = CheckCacheRemote(ref endPointSnapshot, false); // Prepare for the native call. e.StartOperationCommon(this); e.StartOperationSendTo(); // Make the native call. int bytesTransferred; SocketError socketError; // Wrap native methods with try/catch so event args object can be cleaned up. try { socketError = e.DoOperationSendTo(_handle, out bytesTransferred); } catch (Exception ex) { // Clear in-use flag on event args object. e.Complete(); throw ex; } // Handle completion when completion port is not posted. if (socketError != SocketError.Success && socketError != SocketError.IOPending) { e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None); retval = false; } else { retval = true; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "SendToAsync", retval); } return retval; }
public bool AcceptAsync(SocketAsyncEventArgs e) { bool flag; int num; if (s_LoggingEnabled) { Logging.Enter(Logging.Sockets, this, "AcceptAsync", ""); } if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } if (e.m_BufferList != null) { throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList"); } if (this.m_RightEndPoint == null) { throw new InvalidOperationException(SR.GetString("net_sockets_mustbind")); } if (!this.isListening) { throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten")); } if (e.AcceptSocket == null) { e.AcceptSocket = new Socket(this.addressFamily, this.socketType, this.protocolType); } else if ((e.AcceptSocket.m_RightEndPoint != null) && !e.AcceptSocket.m_IsDisconnected) { throw new InvalidOperationException(SR.GetString("net_sockets_namedmustnotbebound", new object[] { "AcceptSocket" })); } e.StartOperationCommon(this); e.StartOperationAccept(); this.BindToCompletionPort(); SocketError success = SocketError.Success; try { if (!this.AcceptEx(this.m_Handle, e.AcceptSocket.m_Handle, (e.m_PtrSingleBuffer != IntPtr.Zero) ? e.m_PtrSingleBuffer : e.m_PtrAcceptBuffer, (e.m_PtrSingleBuffer != IntPtr.Zero) ? (e.Count - e.m_AcceptAddressBufferCount) : 0, e.m_AcceptAddressBufferCount / 2, e.m_AcceptAddressBufferCount / 2, out num, e.m_PtrNativeOverlapped)) { success = (SocketError) Marshal.GetLastWin32Error(); } } catch (Exception exception) { e.Complete(); throw exception; } if ((success != SocketError.Success) && (success != SocketError.IOPending)) { e.FinishOperationSyncFailure(success, num, SocketFlags.None); flag = false; } else { flag = true; } if (s_LoggingEnabled) { Logging.Exit(Logging.Sockets, this, "AcceptAsync", flag); } return flag; }