Socket.BeginAccept Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Begins an asynchronous operation to accept an incoming connection attempt.
Overloads
BeginAccept(AsyncCallback, Object) |
Begins an asynchronous operation to accept an incoming connection attempt. |
BeginAccept(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. |
BeginAccept(Socket, Int32, AsyncCallback, Object) |
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. |
BeginAccept(AsyncCallback, Object)
Begins an asynchronous operation to accept an incoming connection attempt.
public:
IAsyncResult ^ BeginAccept(AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (AsyncCallback? callback, object? state);
public IAsyncResult BeginAccept (AsyncCallback callback, object state);
member this.BeginAccept : AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
- callback
- AsyncCallback
The AsyncCallback delegate.
- state
- Object
An object that contains state information for this request.
Returns
An IAsyncResult that references the asynchronous Socket creation.
Exceptions
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(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).
-or-
The accepted socket is bound.
receiveSize
is less than 0.
.NET Framework and .NET 5 and earlier only: An error occurred when attempting to access the socket.
Examples
The following code example attempts to receive an incoming connection asynchronously.
IPHostEntry^ lipa = Dns::Resolve( "host.contoso.com" );
IPEndPoint^ lep = gcnew IPEndPoint( lipa->AddressList[ 0 ], 11000 );
Socket^ s = gcnew 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( gcnew AsyncCallback( &Async_Send_Receive::Connect_Callback ), s );
allDone->WaitOne();
}
}
catch ( Exception^ e )
{
Console::WriteLine( e );
}
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());
}
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
Remarks
Important
This is a compatibility API. We don't recommend using the APM (Begin*
and End*
) methods for new development. Instead, use the Task
-based equivalents.
Connection-oriented protocols can use the BeginAccept method to start accepting incoming connection attempts. Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.
You can pass a callback that implements AsyncCallback to BeginAccept in order to get notified about the completion of the accept operation. Note that if the underlying network stack completes the operation synchronously, the callback might be executed inline, during the call to BeginAccept. In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to true
to indicate that the method completed synchronously. Use the AsyncState property of the IAsyncResult to obtain the state object passed to the BeginAccept method.
The BeginAccept operation must be completed by calling the EndAccept method. Typically, the method is invoked by the provided AsyncCallback delegate. EndAccept will block the calling thread until the operation is completed.
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 (before .NET 7) or a SocketException (on .NET 7+) to indicate that the operation has been cancelled.
Note
You can use the RemoteEndPoint property of the returned Socket to identify the remote host's network address and port number.
Note
If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code.
Note
This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.
Note
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.
See also
- Listen(Int32)
- AsyncCallback
- EndAccept(IAsyncResult)
- Socket
- RemoteEndPoint
- Asynchronous Client Socket Example
- Asynchronous Server Socket Example
Applies to
BeginAccept(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.
public:
IAsyncResult ^ BeginAccept(int receiveSize, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (int receiveSize, AsyncCallback? callback, object? state);
public IAsyncResult BeginAccept (int receiveSize, AsyncCallback callback, object state);
member this.BeginAccept : int * AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (receiveSize As Integer, callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
- receiveSize
- Int32
The number of bytes to accept from the sender.
- callback
- AsyncCallback
The AsyncCallback delegate.
- state
- Object
An object that contains state information for this request.
Returns
An IAsyncResult that references the asynchronous Socket creation.
Exceptions
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(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).
-or-
The accepted socket is bound.
receiveSize
is less than 0.
.NET Framework and .NET 5 and earlier only: An error occurred when attempting to access the socket.
Examples
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.
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
Important
This is a compatibility API. We don't recommend using the APM (Begin*
and End*
) methods for new development. Instead, use the Task
-based equivalents.
Connection-oriented protocols can use the BeginAccept method to start accepting incoming connection attempts. Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.
You can pass a callback that implements AsyncCallback to BeginAccept in order to get notified about the completion of the accept operation. Note that if the underlying network stack completes the operation synchronously, the callback might be executed inline, during the call to BeginAccept. In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to true
to indicate that the method completed synchronously. Use the AsyncState property of the IAsyncResult to obtain the state object passed to the BeginAccept method.
The BeginAccept operation must be completed by calling the EndAccept method. Typically, the method is invoked by the provided AsyncCallback delegate. EndAccept will block the calling thread until the operation is completed.
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 (before .NET 7) or a SocketException (on .NET 7+) to indicate that the operation has been cancelled.
Note
You can use the RemoteEndPoint property of the returned Socket to identify the remote host's network address and port number.
Note
If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code.
Note
This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.
Note
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.
See also
- Listen(Int32)
- AsyncCallback
- EndAccept(IAsyncResult)
- Socket
- RemoteEndPoint
- Asynchronous Client Socket Example
- Asynchronous Server Socket Example
Applies to
BeginAccept(Socket, Int32, AsyncCallback, Object)
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.
public:
IAsyncResult ^ BeginAccept(System::Net::Sockets::Socket ^ acceptSocket, int receiveSize, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (System.Net.Sockets.Socket? acceptSocket, int receiveSize, AsyncCallback? callback, object? state);
public IAsyncResult BeginAccept (System.Net.Sockets.Socket acceptSocket, int receiveSize, AsyncCallback callback, object state);
member this.BeginAccept : System.Net.Sockets.Socket * int * AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (acceptSocket As Socket, receiveSize As Integer, callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
- receiveSize
- Int32
The maximum number of bytes to receive.
- callback
- AsyncCallback
The AsyncCallback delegate.
- state
- Object
An object that contains state information for this request.
Returns
An IAsyncResult object that references the asynchronous Socket object creation.
Exceptions
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(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).
-or-
The accepted socket is bound.
receiveSize
is less than 0.
.NET Framework and .NET 5 and earlier only: An error occurred when attempting to access the socket.
Examples
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 null
, 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::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.
// BeginAccept() creates the accepted socket.
int receivedDataSize = 10;
listener->BeginAccept( nullptr, receivedDataSize, gcnew AsyncCallback( AcceptReceiveDataCallback ), listener );
// Wait until a connection is made and processed before continuing.
allDone->WaitOne();
}
}
static void AcceptReceiveDataCallback( 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.
// 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);
}
Remarks
Important
This is a compatibility API. We don't recommend using the APM (Begin*
and End*
) methods for new development. Instead, use the Task
-based equivalents.
Connection-oriented protocols can use the BeginAccept method to start accepting incoming connection attempts. The resulting accept operation is represented by the returned IAsyncResult even though it may complete synchronously. Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.
You can pass a callback that implements AsyncCallback to BeginAccept in order to get notified about the completion of the accept operation. Note that if the underlying network stack completes the operation synchronously, the callback might be executed inline, during the call to BeginAccept. In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to true
to indicate that the method completed synchronously. Use the AsyncState property of the IAsyncResult to obtain the state object passed to the BeginAccept method.
The BeginAccept operation must be completed by calling the EndAccept method. Typically, the method is invoked by the provided AsyncCallback delegate. EndAccept will block the calling thread until the operation is completed.
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 (before .NET 7) or a SocketException (on .NET 7+) to indicate that the operation has been cancelled.
Note
You can use the RemoteEndPoint property of the returned Socket to identify the remote host's network address and port number.
Note
If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code.
Note
This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in .NET Framework.
Note
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.
See also
- Listen(Int32)
- AsyncCallback
- EndAccept(IAsyncResult)
- Socket
- RemoteEndPoint
- Asynchronous Client Socket Example
- Asynchronous Server Socket Example