Socket.BeginConnect Socket.BeginConnect Socket.BeginConnect Socket.BeginConnect Method

Definition

Begins an asynchronous request for a remote host connection.

Overloads

BeginConnect(EndPoint, AsyncCallback, Object) BeginConnect(EndPoint, AsyncCallback, Object) BeginConnect(EndPoint, AsyncCallback, Object) BeginConnect(EndPoint, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection.

BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress and a port number.

BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress array and a port number.

BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by a host name and a port number.

BeginConnect(EndPoint, AsyncCallback, Object) BeginConnect(EndPoint, AsyncCallback, Object) BeginConnect(EndPoint, AsyncCallback, Object) BeginConnect(EndPoint, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection.

public:
 IAsyncResult ^ BeginConnect(System::Net::EndPoint ^ end_point, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginConnect (System.Net.EndPoint end_point, AsyncCallback callback, object state);
member this.BeginConnect : System.Net.EndPoint * AsyncCallback * obj -> IAsyncResult
Public Function BeginConnect (end_point As EndPoint, callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
remoteEP
EndPoint EndPoint EndPoint EndPoint

An EndPoint that represents the remote host.

state
Object Object Object Object

An object that contains state information for this request.

Returns

An IAsyncResult that references the asynchronous connection.

Exceptions

An error occurred when attempting to access the socket.

A caller higher in the call stack does not have permission for the requested operation.

The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

Examples

The following code example initiates an asynchronous connection attempt.

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
{
   while ( true )
   {
      allDone->Reset();

      Console::WriteLine( "Establishing Connection" );
      s->BeginConnect( lep, 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{
         
                while(true){
                allDone.Reset();

                Console.WriteLine("Establishing Connection");
                s.BeginConnect(lep, new AsyncCallback(Async_Send_Receive.Connect_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
      
      While True
         allDone.Reset()
         
         Console.WriteLine("Establishing Connection")

         s.BeginConnect(lep, New AsyncCallback(AddressOf Async_Send_Receive.Connect_Callback), s)
         
         allDone.WaitOne()
      End While
   Catch e As Exception
      Console.WriteLine(e.ToString())
   End Try
End Sub 'Connect

Remarks

If you are using a connection-oriented protocol, the BeginConnect method starts an asynchronous request for a connection to the remoteEP parameter. If you are using a connectionless protocol, BeginConnect establishes a default remote host. Connecting or setting the default remote host asynchronously gives you the ability to send and receive data within a separate execution thread.

You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginConnect method. At the very minimum, you must pass the Socket to BeginConnect 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 BeginConnect method through the state parameter.

Your callback method should invoke the EndConnect method. When your application calls BeginConnect, the system will use a separate thread to execute the specified callback method, and will block on EndConnect until the Socket connects successfully or throws an exception. If you want the original thread to block after you call the BeginConnect method, use 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 Marshaling a Delegate as a Callback Method.

If you are using a connectionless protocol such as UDP, you do not have to call BeginConnect before sending and receiving data. You can use BeginSendTo and BeginReceiveFrom to communicate with a remote host. If you do call BeginConnect, any datagrams that arrive from an address other than the specified default will be discarded. If you wish to set your default remote host to a broadcast address, you must first call SetSocketOption and set Broadcast to true. If you cannot, BeginConnect will throw a SocketException.

If you are using a connection-oriented protocol and do not call Bind before calling BeginConnect, the underlying service provider will assign the most appropriate local network address and port number. If you are using a connectionless protocol, the service provider will not assign a local network address and port number until you call the BeginSend or ReceiveFrom method. If you want to change the default remote host, call the BeginConnect method again with the desired endpoint.

To cancel a pending call to the BeginConnect method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

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

If this socket has previously been disconnected, then BeginConnect must be called on a thread that will not exit until the operation is complete. This is a limitation of the underlying provider.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .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

BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object) BeginConnect(IPAddress, Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress and a port number.

public:
 IAsyncResult ^ BeginConnect(System::Net::IPAddress ^ address, int port, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginConnect (System.Net.IPAddress address, int port, AsyncCallback callback, object state);
member this.BeginConnect : System.Net.IPAddress * int * AsyncCallback * obj -> IAsyncResult
Public Function BeginConnect (address As IPAddress, port As Integer, callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
address
IPAddress IPAddress IPAddress IPAddress

The IPAddress of the remote host.

port
Int32 Int32 Int32 Int32

The port number of the remote host.

requestCallback
AsyncCallback AsyncCallback AsyncCallback AsyncCallback

An AsyncCallback delegate that references the method to invoke when the connect operation is complete.

state
Object Object Object Object

A user-defined object that contains information about the connect operation. This object is passed to the requestCallback delegate when the operation is complete.

Returns

An IAsyncResult that references the asynchronous connection.

Exceptions

An error occurred when attempting to access the socket.

The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

Examples

The following code example initiates an asynchronous connection attempt.

static ManualResetEvent^ allDone = gcnew ManualResetEvent( false );

// handles the completion of the prior asynchronous 
// connect call. the socket is passed via the objectState 
// paramater of BeginConnect().
static void ConnectCallback1( IAsyncResult^ ar )
{
   allDone->Set();
   Socket^ s = dynamic_cast<Socket^>(ar->AsyncState);
   s->EndConnect( ar );
}


public static ManualResetEvent allDone = 
    new ManualResetEvent(false);

// handles the completion of the prior asynchronous 
// connect call. the socket is passed via the objectState 
// paramater of BeginConnect().
public static void ConnectCallback1(IAsyncResult ar)
{
    allDone.Set();
    Socket s = (Socket) ar.AsyncState;
    s.EndConnect(ar);
}
// Asynchronous connect using the host name, resolved via 
// IPAddress
static void BeginConnect1( String^ host, int port )
{
   array<IPAddress^>^IPs = Dns::GetHostAddresses( host );
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   allDone->Reset();
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->BeginConnect( IPs[ 0 ], port, gcnew AsyncCallback( ConnectCallback1 ), s );
   
   // wait here until the connect finishes.  
   // The callback sets allDone.
   allDone->WaitOne();
   Console::WriteLine( "Connection established" );
}


// Asynchronous connect using the host name, resolved via 
// IPAddress
public static void BeginConnect1(string host, int port)
{

    IPAddress[] IPs = Dns.GetHostAddresses(host);

    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);

    allDone.Reset();

    Console.WriteLine("Establishing Connection to {0}", 
        host);
    s.BeginConnect(IPs[0], port, 
        new AsyncCallback(ConnectCallback1), s);

    // wait here until the connect finishes.  
    // The callback sets allDone.
    allDone.WaitOne();

    Console.WriteLine("Connection established");

}		

Remarks

The asynchronous BeginConnect operation must be completed by calling the EndConnect method. Typically, the method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use one of the Connect method overloads, or EndConnect.

To cancel a pending call to the BeginConnect method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously

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

If this socket has previously been disconnected, then BeginConnect must be called on a thread that will not exit until the operation is complete. This is a limitation of the underlying provider. Also the EndPoint that is used must be different.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .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

BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object) BeginConnect(IPAddress[], Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by an IPAddress array and a port number.

public:
 IAsyncResult ^ BeginConnect(cli::array <System::Net::IPAddress ^> ^ addresses, int port, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginConnect (System.Net.IPAddress[] addresses, int port, AsyncCallback callback, object state);
member this.BeginConnect : System.Net.IPAddress[] * int * AsyncCallback * obj -> IAsyncResult
Public Function BeginConnect (addresses As IPAddress(), port As Integer, callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
addresses
IPAddress[]

At least one IPAddress, designating the remote host.

port
Int32 Int32 Int32 Int32

The port number of the remote host.

requestCallback
AsyncCallback AsyncCallback AsyncCallback AsyncCallback

An AsyncCallback delegate that references the method to invoke when the connect operation is complete.

state
Object Object Object Object

A user-defined object that contains information about the connect operation. This object is passed to the requestCallback delegate when the operation is complete.

Returns

An IAsyncResult that references the asynchronous connections.

Exceptions

An error occurred when attempting to access the socket.

The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

Examples

The following code example initiates an asynchronous connection attempt.

static ManualResetEvent^ allDone = gcnew ManualResetEvent( false );

// handles the completion of the prior asynchronous 
// connect call. the socket is passed via the objectState 
// paramater of BeginConnect().
static void ConnectCallback1( IAsyncResult^ ar )
{
   allDone->Set();
   Socket^ s = dynamic_cast<Socket^>(ar->AsyncState);
   s->EndConnect( ar );
}


public static ManualResetEvent allDone = 
    new ManualResetEvent(false);

// handles the completion of the prior asynchronous 
// connect call. the socket is passed via the objectState 
// paramater of BeginConnect().
public static void ConnectCallback1(IAsyncResult ar)
{
    allDone.Set();
    Socket s = (Socket) ar.AsyncState;
    s.EndConnect(ar);
}
// Asynchronous connect, using DNS.ResolveToAddresses
static void BeginConnect2( String^ host, int port )
{
   array<IPAddress^>^IPs = Dns::GetHostAddresses( host );
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   allDone->Reset();
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->BeginConnect( IPs, port, gcnew AsyncCallback( ConnectCallback1 ), s );
   
   // wait here until the connect finishes.  The callback 
   // sets allDone.
   allDone->WaitOne();
   Console::WriteLine( "Connection established" );
}



// Asynchronous connect, using DNS.GetHostAddresses
public static void BeginConnect2(string host, int port)
{
    IPAddress[] IPs = Dns.GetHostAddresses(host);

    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);

    allDone.Reset();

    Console.WriteLine("Establishing Connection to {0}", 
        host);
    s.BeginConnect(IPs, port, 
        new AsyncCallback(ConnectCallback1), s);

    // wait here until the connect finishes.  The callback 
    // sets allDone.
    allDone.WaitOne();

    Console.WriteLine("Connection established");
}		

Remarks

The asynchronous BeginConnect operation must be completed by calling the EndConnect method. Typically, the method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use one of the Connect method overloads.

To cancel a pending call to the BeginConnect method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

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

If this socket has previously been disconnected, then BeginConnect must be called on a thread that will not exit until the operation is complete. This is a limitation of the underlying provider. Also the EndPoint that is used must be different.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .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

BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object) BeginConnect(String, Int32, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection. The host is specified by a host name and a port number.

public:
 IAsyncResult ^ BeginConnect(System::String ^ host, int port, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginConnect (string host, int port, AsyncCallback callback, object state);
member this.BeginConnect : string * int * AsyncCallback * obj -> IAsyncResult
Public Function BeginConnect (host As String, port As Integer, callback As AsyncCallback, state As Object) As IAsyncResult
Parameters
host
String String String String

The name of the remote host.

port
Int32 Int32 Int32 Int32

The port number of the remote host.

requestCallback
AsyncCallback AsyncCallback AsyncCallback AsyncCallback

An AsyncCallback delegate that references the method to invoke when the connect operation is complete.

state
Object Object Object Object

A user-defined object that contains information about the connect operation. This object is passed to the requestCallback delegate when the operation is complete.

Returns

An IAsyncResult that references the asynchronous connection.

Exceptions

The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

Examples

The following code example initiates an asynchronous connection attempt.

static ManualResetEvent^ allDone = gcnew ManualResetEvent( false );

// handles the completion of the prior asynchronous 
// connect call. the socket is passed via the objectState 
// paramater of BeginConnect().
static void ConnectCallback1( IAsyncResult^ ar )
{
   allDone->Set();
   Socket^ s = dynamic_cast<Socket^>(ar->AsyncState);
   s->EndConnect( ar );
}


public static ManualResetEvent allDone = 
    new ManualResetEvent(false);

// handles the completion of the prior asynchronous 
// connect call. the socket is passed via the objectState 
// paramater of BeginConnect().
public static void ConnectCallback1(IAsyncResult ar)
{
    allDone.Set();
    Socket s = (Socket) ar.AsyncState;
    s.EndConnect(ar);
}
// Asynchronous connect using host name (resolved by the 
// BeginConnect call.)
static void BeginConnect3( String^ host, int port )
{
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   allDone->Reset();
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->BeginConnect( host, port, gcnew AsyncCallback( ConnectCallback1 ), s );
   
   // wait here until the connect finishes.  The callback 
   // sets allDone.
   allDone->WaitOne();
   Console::WriteLine( "Connection established" );
}


// Asynchronous connect using host name (resolved by the 
// BeginConnect call.)
public static void BeginConnect3(string host, int port)
{
    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);

    allDone.Reset();

    Console.WriteLine("Establishing Connection to {0}", 
        host);
    s.BeginConnect(host, port, 
        new AsyncCallback(ConnectCallback1), s);

    // wait here until the connect finishes.  The callback 
    // sets allDone.
    allDone.WaitOne();

    Console.WriteLine("Connection established");
}		

Remarks

The asynchronous BeginConnect operation must be completed by calling the EndConnect method. Typically, the method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use one of the Connect method overloads.

To cancel a pending call to the BeginConnect method, close the Socket. When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously

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

If this socket has previously been disconnected, then BeginConnect must be called on a thread that will not exit until the operation is complete. This is a limitation of the underlying provider. Also the EndPoint that is used must be different.

Note

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing in the .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

Applies to