Export (0) Print
Expand All

Socket.BeginConnect Method

Begins an asynchronous request for a remote host connection.

[Visual Basic]
Public Function BeginConnect( _
   ByVal remoteEP As EndPoint, _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginConnect(
 EndPoint remoteEP,
 AsyncCallback callback,
 object state
);
[C++]
public: IAsyncResult* BeginConnect(
 EndPoint* remoteEP,
 AsyncCallback* callback,
 Object* state
);
[JScript]
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.

Exceptions

Exception Type Condition
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.

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 acallback 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 implement 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 Set 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.

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

[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
   
   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

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

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

        Console::WriteLine(S"Establishing Connection");
        AsyncCallback* pasync = new AsyncCallback(0, &Async_Send_Receive::Connect_Callback);
        s->BeginConnect(lep, 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 | Callback Sample | AsyncCallback | EndConnect | BeginSendTo | BeginReceiveFrom

Show:
© 2014 Microsoft