Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Socket.BeginConnect Method (EndPoint, AsyncCallback, Object)

Begins an asynchronous request for a remote host connection.

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

public IAsyncResult BeginConnect (
	EndPoint remoteEP,
	AsyncCallback callback,
	Object state
)
public IAsyncResult BeginConnect (
	EndPoint remoteEP, 
	AsyncCallback callback, 
	Object state
)
public function BeginConnect (
	remoteEP : EndPoint, 
	callback : AsyncCallback, 
	state : Object
) : IAsyncResult

Parameters

remoteEP

An EndPoint that represents the remote host.

callback

The AsyncCallback delegate.

state

An object that contains state information for this request.

Return Value

An IAsyncResult that references the asynchronous connection.

Exception typeCondition

ArgumentNullException

remoteEP is a null reference (Nothing in Visual Basic).

SocketException

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

ObjectDisposedException

The Socket has been closed.

SecurityException

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

InvalidOperationException

The Socket is Listening.

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 T:System.Threading.ManualResetEvent in the callback method when you want the original thread to continue executing. For additional information on writing callback methods see Callback Sample.

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.

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 the MSDN library for a detailed description of the error.

NoteNote

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.

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 initiates an asynchronous connection attempt.

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());
   }

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

Socket s = new Socket(lep.get_Address().get_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 (System.Exception e) {
    Console.WriteLine(e.ToString());
}

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

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

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft