Export (0) Print
Expand All

Socket.BeginAccept Method (AsyncCallback, Object)

Begins an asynchronous operation to accept an incoming connection attempt.

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

[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public IAsyncResult BeginAccept(
	AsyncCallback callback,
	Object state
)

Parameters

callback
Type: System.AsyncCallback

The AsyncCallback delegate.

state
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.

ExceptionCondition
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.

NoteNote:

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.

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. 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 will return 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.

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.

NoteNote:

You can use the RemoteEndPoint property of the returned Socket 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 MSDN 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 attempts to receive an incoming connection asynchronously.

	IPHostEntry lipa = Dns.Resolve("host.contoso.com");
	IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

       Socket s = new Socket(lep.Address.AddressFamily,
       	                           SocketType.Stream,
                                         ProtocolType.Tcp);
       try{
            s.Bind(lep);
            s.Listen(1000);

            while(true){
                 allDone.Reset();

                 Console.WriteLine("Waiting for a connection...");
                 s.BeginAccept(new AsyncCallback(Async_Send_Receive.Listen_Callback), s);

                 allDone.WaitOne();
            }
       }
       catch (Exception e){
            Console.WriteLine(e.ToString());
       }
IPHostEntry* lipa = Dns::Resolve(S"host.contoso.com");
IPEndPoint* lep = new IPEndPoint(lipa->AddressList[0], 11000);

Socket* s = new Socket(lep->Address->AddressFamily,
    SocketType::Stream,
    ProtocolType::Tcp);

try {
    s->Bind(lep);
    s->Listen(1000);

    while (true) {
        allDone->Reset();

        Console::WriteLine(S"Waiting for a connection...");
        AsyncCallback* pasync = new AsyncCallback(0, &Async_Send_Receive::Listen_Callback);
        s->BeginAccept(pasync, s);

        allDone->WaitOne();
    }
} catch (Exception* e) {
    Console::WriteLine(e);
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

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

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

Community Additions

ADD
Show:
© 2015 Microsoft