Socket.EndAccept Socket.EndAccept Socket.EndAccept Socket.EndAccept Method

Definition

Asynchronously accepts an incoming connection attempt.

Overloads

EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data transferred.

EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data and the number of bytes transferred.

EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult) EndAccept(Byte[], IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data transferred.

public:
 System::Net::Sockets::Socket ^ EndAccept([Runtime::InteropServices::Out] cli::array <System::Byte> ^ % buffer, IAsyncResult ^ asyncResult);
public System.Net.Sockets.Socket EndAccept (out byte[] buffer, IAsyncResult asyncResult);
member this.EndAccept :  * IAsyncResult -> System.Net.Sockets.Socket
Public Function EndAccept (ByRef buffer As Byte(), asyncResult As IAsyncResult) As Socket
Parameters
buffer
Byte[]

An array of type Byte that contains the bytes transferred.

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

An IAsyncResult object that stores state information for this asynchronous operation as well as any user defined data.

Returns

A Socket object to handle communication with the remote host.

Exceptions

An error occurred when attempting to access the Socket

Examples

The following code example uses BeginAccept to create and connect a socket and accept the initial 10 bytes of data. The callback delegate calls EndAccept to end the asynchronous request. The number of bytes transmitted and the data are returned in the buffer and bytesTransferred parameters of this method and are displayed on the console.

   // 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::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   IPEndPoint^ localEndPoint = gcnew IPEndPoint( ipAddress,11000 );
   
   // Create a TCP/IP socket.
   Socket^ listener = gcnew 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 );
   for ( ; ;  )
   {
      
      // 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.
      int receivedDataSize = 10;
      listener->BeginAccept( receivedDataSize, gcnew AsyncCallback( AcceptReceiveCallback ), listener );
      
      // Wait until a connection is made and processed before continuing.
      allDone->WaitOne();

   }
}

static void AcceptReceiveCallback( IAsyncResult^ ar )
{
   // Get the socket that handles the client request.
   Socket^ listener = dynamic_cast<Socket^>(ar->AsyncState);

   // End the operation and display the received data on the console.
   array<Byte>^Buffer;
   int bytesTransferred;
   Socket^ handler = listener->EndAccept( Buffer, 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 = gcnew StateObject;
   state->workSocket = handler;
   handler->BeginReceive( state->buffer, 0, StateObject::BufferSize, static_cast<SocketFlags>(0), gcnew AsyncCallback( ReadCallback ), state );
}


    // 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.GetHostEntry(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.
        int receivedDataSize = 10;
        listener.BeginAccept(receivedDataSize, new AsyncCallback(AcceptReceiveCallback), listener);
         
        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }

}


public static void AcceptReceiveCallback(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);
}

Remarks

EndAccept completes a call to BeginAccept. Before calling BeginAccept, you need to create a callback method that is invoked by the AsyncCallback delegate. This callback method executes in a separate thread, and is called by the system after the BeginAccept method returns.

Within the callback method, call the AsyncState method of the asyncResult parameter to obtain the Socket on which the connection attempt is being made. After obtaining the Socket, you can call the EndAccept method to successfully complete the connection attempt. The buffer parameter of this overload contains the data that was received in the call to BeginAccept and the bytesTransferred parameter contains the number of bytes that were transferred in the call.

The EndAccept method blocks until a connection is pending in the incoming connection queue. The EndAccept method accepts the incoming connection and returns a new Socket that can be used to send data to and receive data from the remote host.

Note

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.

Note

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

EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult) EndAccept(IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.

public:
 System::Net::Sockets::Socket ^ EndAccept(IAsyncResult ^ result);
public System.Net.Sockets.Socket EndAccept (IAsyncResult result);
member this.EndAccept : IAsyncResult -> System.Net.Sockets.Socket
Public Function EndAccept (result As IAsyncResult) As Socket
Parameters
asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

An IAsyncResult that stores state information for this asynchronous operation as well as any user defined data.

Returns

A Socket to handle communication with the remote host.

Exceptions

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

Examples

The following code example ends an asynchronous request and creates a new Socket to accept an incoming connection request. For a complete example that demonstrates asynchronous communications with sockets, see Socket Code Examples.

static void Listen_Callback( IAsyncResult^ ar )
{
   allDone->Set();
   Socket^ s = safe_cast<Socket^>(ar->AsyncState);
   Socket^ s2 = s->EndAccept( ar );
   StateObject^ so2 = gcnew StateObject;
   so2->workSocket = s2;
   s2->BeginReceive( so2->buffer, 0, StateObject::BUFFER_SIZE, SocketFlags::None,
      gcnew AsyncCallback( &Async_Send_Receive::Read_Callback ), so2 );
}
public static void Listen_Callback(IAsyncResult ar){
     allDone.Set();
     Socket s = (Socket) ar.AsyncState;
     Socket s2 = s.EndAccept(ar);
     StateObject so2 = new StateObject();
     so2.workSocket = s2;
     s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE,0,
	                       new AsyncCallback(Async_Send_Receive.Read_Callback), so2);	
}
Public Shared Sub Listen_Callback(ar As IAsyncResult)
   allDone.Set()
   Dim s As Socket = CType(ar.AsyncState, Socket)
   Dim s2 As Socket = s.EndAccept(ar)
   Dim so2 As New StateObject()
   so2.workSocket = s2
   s2.BeginReceive(so2.buffer, 0, StateObject.BUFFER_SIZE, 0, New AsyncCallback(AddressOf Async_Send_Receive.Read_Callback), so2)
End Sub 'Listen_Callback

Remarks

EndAccept completes a call to BeginAccept. Before calling BeginAccept, you need to create a callback method that implements the AsyncCallback delegate. This callback method executes in a separate thread, and is called by the system after the BeginAccept method returns. It must accept the asyncResult parameter returned from the BeginAccept method.

Within the callback method, call the AsyncState method of the asyncResult parameter to obtain the Socket on which the connection attempt is being made. After obtaining the Socket, you can call the EndAccept method to successfully complete the connection attempt.

The EndAccept method blocks until a connection is pending in the incoming connection queue. The EndAccept method accepts the incoming connection and returns a new Socket that can be used to send data to and receive data from the remote host.

Note

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.

Note

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

See Also

EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult) EndAccept(Byte[], Int32, IAsyncResult)

Asynchronously accepts an incoming connection attempt and creates a new Socket object to handle remote host communication. This method returns a buffer that contains the initial data and the number of bytes transferred.

public:
 System::Net::Sockets::Socket ^ EndAccept([Runtime::InteropServices::Out] cli::array <System::Byte> ^ % buffer, [Runtime::InteropServices::Out] int % bytesTransferred, IAsyncResult ^ asyncResult);
public System.Net.Sockets.Socket EndAccept (out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult);
member this.EndAccept :  *  * IAsyncResult -> System.Net.Sockets.Socket
Public Function EndAccept (ByRef buffer As Byte(), ByRef bytesTransferred As Integer, asyncResult As IAsyncResult) As Socket
Parameters
buffer
Byte[]

An array of type Byte that contains the bytes transferred.

bytesTransferred
Int32 Int32 Int32 Int32

The number of bytes transferred.

asyncResult
IAsyncResult IAsyncResult IAsyncResult IAsyncResult

An IAsyncResult object that stores state information for this asynchronous operation as well as any user defined data.

Returns

A Socket object to handle communication with the remote host.

Exceptions

An error occurred when attempting to access the Socket.

Examples

The following code example uses BeginAccept to create and connect a socket and accept the initial 10 bytes of data. The callback delegate calls EndAccept to end the asynchronous request. The number of bytes transmitted and the data are returned in the buffer and bytesTransferred parameters of this method and are displayed on the console.

   // 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::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   IPEndPoint^ localEndPoint = gcnew IPEndPoint( ipAddress,11000 );
   
   // Create a TCP/IP socket.
   Socket^ listener = gcnew 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 );
   for ( ; ;  )
   {
      
      // 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.
      int receivedDataSize = 10;
      listener->BeginAccept( receivedDataSize, gcnew AsyncCallback( AcceptReceiveCallback ), listener );
      
      // Wait until a connection is made and processed before continuing.
      allDone->WaitOne();

   }
}

static void AcceptReceiveCallback( IAsyncResult^ ar )
{
   // Get the socket that handles the client request.
   Socket^ listener = dynamic_cast<Socket^>(ar->AsyncState);

   // End the operation and display the received data on the console.
   array<Byte>^Buffer;
   int bytesTransferred;
   Socket^ handler = listener->EndAccept( Buffer, 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 = gcnew StateObject;
   state->workSocket = handler;
   handler->BeginReceive( state->buffer, 0, StateObject::BufferSize, static_cast<SocketFlags>(0), gcnew AsyncCallback( ReadCallback ), state );
}


    // 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.GetHostEntry(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.
        int receivedDataSize = 10;
        listener.BeginAccept(receivedDataSize, new AsyncCallback(AcceptReceiveCallback), listener);
         
        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }

}


public static void AcceptReceiveCallback(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);
}

Remarks

EndAccept completes a call to BeginAccept. Before calling BeginAccept, you need to create a callback method that is invoked by the AsyncCallback delegate. This callback method executes in a separate thread, and is called by the system after the BeginAccept method returns. It must accept the asyncResult parameter returned from the BeginAccept method.

Within the callback method, call the AsyncState method of the asyncResult parameter to obtain the Socket on which the connection attempt is being made. After obtaining the Socket, you can call the EndAccept method to successfully complete the connection attempt. The buffer parameter of this overload contains the data that was received in the call to BeginAccept and the bytesTransferred parameter contains the number of bytes that were transferred in the call.

The EndAccept method blocks until a connection is pending in the incoming connection queue. The EndAccept method accepts the incoming connection and returns a new Socket that can be used to send data to and receive data from the remote host.

Note

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.

Note

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

Applies to