This documentation is archived and is not being maintained.

Socket.BeginAccept Method (Int32, AsyncCallback, Object)

Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)

<HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading := True)> _
Public Function BeginAccept ( _
	receiveSize As Integer, _
	callback As AsyncCallback, _
	state As Object _
) As IAsyncResult


Type: System.Int32
The number of bytes to accept from the sender.
Type: System.AsyncCallback
The AsyncCallback delegate.
Type: System.Object
An object that contains state information for this request.

Return Value

Type: System.IAsyncResult
An IAsyncResult that references the asynchronous Socket creation.


The Socket object has been closed.


Windows NT is required for this method.


The accepting socket is not listening for connections. You must call Bind and Listen before calling BeginAccept.


The accepted socket is bound.


receiveSize is less than 0.


An error occurred when attempting to access the socket. See the Remarks section for more information.

Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. Accepting connections asynchronously enables you to send and receive data within a separate execution thread. This overload allows you to specify the number of bytes to accept in the initial transfer in the receiveSize parameter.

Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. To do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. If your callback needs more information, you can create a small class to hold the Socket and the other required information. Pass an instance of this class to the BeginAccept method through the state parameter.

Your callback method should invoke the EndAccept method. When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved.

EndAccept returns a new Socket that you can use to send and receive data with the remote host. You cannot use this returned Socket to accept any additional connections from the connection queue. If you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

The system may also use the calling thread to invoke the callback method. In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

For additional information on writing callback methods see Callback Sample.

To cancel a pending call to the BeginAccept method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.


You can use the RemoteEndPoint property of the returned Socket object to identify the remote host's network address and port number.


If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.


This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing.


The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.


The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

The following code example opens a socket and accepts an asynchronous connection. In this example, the socket accepts the initial 10 bytes of data. The number of bytes received and the data are displayed on the console by the callback delegate. See BeginReceive for a description of how the remaining data is received.

    ' This server waits for a connection and then uses asynchronous operations to
    ' accept the connection with initial data sent from the client.

    ' Establish the local endpoint for the socket.

    Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
    Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
    Dim localEndPoint As New IPEndPoint(ipAddress, 11000)

    ' Create a TCP/IP socket.
    Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    ' Bind the socket to the local endpoint, and listen for incoming connections.

        ' Set the event to nonsignaled state.

        ' Start an asynchronous socket to listen for connections and receive data from the client.
        Console.WriteLine("Waiting for a connection...")

        ' Accept the connection and receive the first 10 bytes of data.
        Dim receivedDataSize As Integer = 10
        listener.BeginAccept(receivedDataSize, New AsyncCallback(AddressOf AcceptReceiveCallback), listener)

        ' Wait until a connection is made and processed before continuing.

End Sub

Public Shared Sub AcceptReceiveCallback(ByVal ar As IAsyncResult)
    ' Get the socket that handles the client request.
    Dim listener As Socket = CType(ar.AsyncState, Socket)

    ' End the operation and display the received data on the console.
    Dim Buffer() As Byte
    Dim bytesTransferred As Integer
    Dim handler As Socket = listener.EndAccept(Buffer, bytesTransferred, ar)
    Dim stringTransferred As String = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred)

    Console.WriteLine("Size of data transferred is {0}", bytesTransferred)

    ' Create the state object for the asynchronous receive.
    Dim state As New StateObject()
    state.workSocket = handler
    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
End Sub

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.