Export (0) Print
Expand All

Socket.BeginAccept Method (Socket, Int32, AsyncCallback, Object)

Note: This method is new in the .NET Framework version 2.0.

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

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

'Declaration
Public Function BeginAccept ( _
	acceptSocket As Socket, _
	receiveSize As Integer, _
	callback As AsyncCallback, _
	state As Object _
) As IAsyncResult
'Usage
Dim instance As Socket
Dim acceptSocket As Socket
Dim receiveSize As Integer
Dim callback As AsyncCallback
Dim state As Object
Dim returnValue As IAsyncResult

returnValue = instance.BeginAccept(acceptSocket, receiveSize, callback, state)
public IAsyncResult BeginAccept (
	Socket acceptSocket, 
	int receiveSize, 
	AsyncCallback callback, 
	Object state
)
public function BeginAccept (
	acceptSocket : Socket, 
	receiveSize : int, 
	callback : AsyncCallback, 
	state : Object
) : IAsyncResult

Parameters

acceptSocket

The accepted Socket object. This value may be a null reference (Nothing in Visual Basic).

receiveSize

The maximum number of bytes to receive.

callback

The AsyncCallback delegate.

state

An object that contains state information for this request.

Return Value

An IAsyncResult object that references the asynchronous Socket object creation.

Exception typeCondition

ObjectDisposedException

The Socket object has been closed.

NotSupportedException

Windows NT is required for this method.

InvalidOperationException

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

-or-

The accepted socket is bound.

ArgumentOutOfRangeException

receiveSize is less than 0.

SocketException

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 gives you the ability to send and receive data within a separate execution thread. This overload allows you to specify the accepted socket in the acceptSocket parameter. If this parameter is a null reference (Nothing in Visual Basic), the accepted socket is created by the BeginAccept method. You can 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 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 object 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. For additional information on writing callback methods, see Callback Sample.

NoteNote

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

NoteNote

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.

NoteNote

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

NoteNote

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 following code example opens a socket and accepts an asynchronous connection. In this example, the socket accepts the initial 10 bytes of data and the acceptSocket parameter is a null reference (Nothing in Visual Basic), which forces the BeginAccept method to create the accepted socket. 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.

    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint, and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(100);

    while (true) 
    {
        // Set the event to nonsignaled state.
        allDone.Reset();

        // 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. 
        // BeginAccept() creates the accepted socket.
        int receivedDataSize = 10;
        listener.BeginAccept(null, receivedDataSize, new AsyncCallback(AcceptReceiveDataCallback), listener);

        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }
}



public static void AcceptReceiveDataCallback(IAsyncResult ar) 
{
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    
    // End the operation and display the received data on the console.
    byte[] Buffer;
    int bytesTransferred;
    Socket handler = listener.EndAccept(out Buffer, out bytesTransferred, ar);
    string stringTransferred = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred);
    
    Console.WriteLine(stringTransferred);
    Console.WriteLine("Size of data transferred is {0}", bytesTransferred);

    // Create the state object for the asynchronous receive.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
    new AsyncCallback(ReadCallback), state);
}


Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0

Community Additions

ADD
Show:
© 2014 Microsoft