Export (0) Print
Expand All
1 out of 4 rated this helpful - Rate this topic

Socket.BeginAccept Method

Begins an asynchronous operation to accept an incoming connection attempt.

[Visual Basic]
Public Function BeginAccept( _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginAccept(
 AsyncCallback callback,
 object state
);
[C++]
public: IAsyncResult* BeginAccept(
 AsyncCallback* callback,
 Object* state
);
[JScript]
public function BeginAccept(
   callback : AsyncCallback,
 state : Object
) : IAsyncResult;

Parameters

callback
The AsyncCallback delegate.
state
An object containing state information for this request.

Return Value

An IAsyncResult that references the asynchronous Socket creation.

Exceptions

Exception Type Condition
SocketException An error occurred when attempting to access the socket. See the Remarks section for more information.
ObjectDisposedException The Socket has been closed.

Remarks

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 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 implement the EndAccept method. When your application calls BeginAccept, the system will use a separate thread to execute the specified callback method, and will block on EndAccept until a pending connection is retrieved. EndAccept will return 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 ManualResetEvent.Set in the callback method when you want the original thread to continue executing. For additional information on writing callback methods see Callback Sample.

Note   You can call the RemoteEndPoint method of the returned Socket to identify the remote host's network address and port number.
Note   If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Once you have obtained this code, you can refer to the Windows Socket Version 2 API error code documentation in MSDN for a detailed description of the error.

Example

[Visual Basic, C#, C++] The following example attempts to receive an incoming connection asynchronously.

[Visual Basic] 
Dim lipa As IPHostEntry = Dns.Resolve("host.contoso.com")
Dim lep As New IPEndPoint(lipa.AddressList(0), 11000)

Dim s As 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(AddressOf Async_Send_Receive.Listen_Callback), s)
      
      allDone.WaitOne()
   End While
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try
   End Sub 'Listen

[C#] 
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());
   }

[C++] 
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);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

Socket Class | Socket Members | System.Net.Sockets Namespace | Including Asynchronous Calls | Listen | AsyncCallback | EndAccept | Socket | RemoteEndPoint

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.