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

定义

开始一个对远程主机连接的异步请求。Begins an asynchronous request for a remote host connection.

重载

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. 主机由 IPAddress 和端口号指定。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. 主机由 IPAddress 数组和端口号指定。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

参数

remoteEP
EndPoint 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.

返回

引用异步连接的 IAsyncResultAn IAsyncResult that references the asynchronous connection.

异常

尝试访问套接字时出错。An error occurred when attempting to access the socket.

调用堆栈中的较高调用方无权执行所请求的操作。A caller higher in the call stack does not have permission for the requested operation.

已通过调用 Listen(Int32)Socket 置于侦听状态,或异步操作已在进行中。The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

示例

下面的代码示例启动异步连接尝试。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

注解

如果使用面向连接的协议BeginConnect方法启动的连接的异步请求remoteEP参数。If you are using a connection-oriented protocol, the BeginConnect method starts an asynchronous request for a connection to the remoteEP parameter. 如果您使用的是无连接协议,BeginConnect建立默认远程主机。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.

可以创建实现一个回调方法AsyncCallback委托并将传递到其名称BeginConnect方法。You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginConnect method. 至少,您必须传递SocketBeginConnect通过state参数。At the very minimum, you must pass the Socket to BeginConnect through the state parameter. 如果回调需要详细信息,可以创建一个小类来保存Socket,和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket, and the other required information. 传递到此类的实例BeginConnect方法通过state参数。Pass an instance of this class to the BeginConnect method through the state parameter.

回调方法应该调用EndConnect方法。Your callback method should invoke the EndConnect method. 当应用程序调用BeginConnect,系统将使用一个单独的线程来执行指定的回调方法,并阻止EndConnect直到Socket已成功连接或引发异常。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. 如果你想要阻止调用后的原始线程BeginConnect方法,请使用WaitOneIf you want the original thread to block after you call the BeginConnect method, use WaitOne. 在调用 Set 方法ManualResetEvent在回调方法时所需的原始线程继续执行。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.

如果使用如 UDP 是无连接协议,不需要调用BeginConnect之前发送和接收数据。If you are using a connectionless protocol such as UDP, you do not have to call BeginConnect before sending and receiving data. 可以使用BeginSendToBeginReceiveFrom与远程主机通信。You can use BeginSendTo and BeginReceiveFrom to communicate with a remote host. 如果调用BeginConnect,将丢弃来自指定的默认值以外的地址的任何数据报。If you do call BeginConnect, any datagrams that arrive from an address other than the specified default will be discarded. 如果你想要将默认远程主机到广播地址,必须先调用SetSocketOption设置为广播和trueIf you wish to set your default remote host to a broadcast address, you must first call SetSocketOption and set Broadcast to true. 如果您不能BeginConnect将引发SocketExceptionIf you cannot, BeginConnect will throw a SocketException.

如果您使用的是面向连接的协议,并且不会调用Bind之前调用BeginConnect,基础服务提供程序将分配的最合适的本地网络地址和端口号。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. 如果您使用的是无连接协议,直到您调用,服务提供程序将不分配本地网络地址和端口号BeginSendReceiveFrom方法。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. 如果你想要更改默认远程主机,则调用BeginConnect方法再次使用所需终结点。If you want to change the default remote host, call the BeginConnect method again with the desired endpoint.

若要取消挂起调用BeginConnect方法,关闭SocketTo cancel a pending call to the BeginConnect method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginConnect调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. 随后调用EndConnect方法将引发ObjectDisposedException以指示已取消该操作。A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

如果以前已断开此套接字,然后BeginConnect必须在操作完成之前不会退出的线程上调用。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.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

另请参阅

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. 主机由 IPAddress 和端口号指定。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

参数

address
IPAddress IPAddress IPAddress IPAddress

远程主机的 IPAddressThe IPAddress of the remote host.

port
Int32 Int32 Int32 Int32

远程主机的端口号。The port number of the remote host.

requestCallback
AsyncCallback 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. 当操作完成时,此对象会被传递给 requestCallback 委托。This object is passed to the requestCallback delegate when the operation is complete.

返回

引用异步连接的 IAsyncResultAn IAsyncResult that references the asynchronous connection.

异常

尝试访问套接字时出错。An error occurred when attempting to access the socket.

Socket 不在套接字族中。The Socket is not in the socket family.

address 的长度为零。The length of address is zero.

已通过调用 Listen(Int32)Socket 置于侦听状态,或异步操作已在进行中。The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

示例

下面的代码示例启动异步连接尝试。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");

}		

注解

异步BeginConnect完成操作,必须通过调用EndConnect方法。The asynchronous BeginConnect operation must be completed by calling the EndConnect method. 通常情况下,通过调用该方法requestCallback委托。Typically, the method is invoked by the requestCallback delegate.

此方法不会阻止,直到完成该操作。This method does not block until the operation is complete. 若要阻止,直到完成该操作后,使用之一Connect方法重载或EndConnectTo block until the operation is complete, use one of the Connect method overloads, or EndConnect.

若要取消挂起调用BeginConnect方法,关闭SocketTo cancel a pending call to the BeginConnect method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginConnect调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. 随后调用EndConnect方法将引发ObjectDisposedException以指示已取消该操作。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

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

如果以前已断开此套接字,然后BeginConnect必须在操作完成之前不会退出的线程上调用。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. 此外EndPoint,它是使用必须不同。Also the EndPoint that is used must be different.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

另请参阅

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. 主机由 IPAddress 数组和端口号指定。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

参数

addresses
IPAddress[]

至少一个用于指定远程主机的 IPAddressAt least one IPAddress, designating the remote host.

port
Int32 Int32 Int32 Int32

远程主机的端口号。The port number of the remote host.

requestCallback
AsyncCallback 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. 当操作完成时,此对象会被传递给 requestCallback 委托。This object is passed to the requestCallback delegate when the operation is complete.

返回

引用异步连接的 IAsyncResultAn IAsyncResult that references the asynchronous connections.

异常

尝试访问套接字时出错。An error occurred when attempting to access the socket.

此方法对使用 InterNetworkInterNetworkV6 的套接字有效。This method is valid for sockets that use InterNetwork or InterNetworkV6.

address 的长度为零。The length of address is zero.

已通过调用 Listen(Int32)Socket 置于侦听状态,或异步操作已在进行中。The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

示例

下面的代码示例启动异步连接尝试。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");
}		

注解

异步BeginConnect完成操作,必须通过调用EndConnect方法。The asynchronous BeginConnect operation must be completed by calling the EndConnect method. 通常情况下,通过调用该方法requestCallback委托。Typically, the method is invoked by the requestCallback delegate.

此方法不会阻止,直到完成该操作。This method does not block until the operation is complete. 若要阻止,直到完成该操作后,使用之一Connect方法重载。To block until the operation is complete, use one of the Connect method overloads.

若要取消挂起调用BeginConnect方法,关闭SocketTo cancel a pending call to the BeginConnect method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginConnect调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. 随后调用EndConnect方法将引发ObjectDisposedException以指示已取消该操作。A subsequent call to the EndConnect method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

有关使用异步编程模型的详细信息,请参阅Calling Synchronous Methods AsynchronouslyFor detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

如果以前已断开此套接字,然后BeginConnect必须在操作完成之前不会退出的线程上调用。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. 此外EndPoint,它是使用必须不同。Also the EndPoint that is used must be different.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

另请参阅

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

参数

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

一个 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. 当操作完成时,此对象会被传递给 requestCallback 委托。This object is passed to the requestCallback delegate when the operation is complete.

返回

引用异步连接的 IAsyncResultAn IAsyncResult that references the asynchronous connection.

异常

此方法对 InterNetworkInterNetworkV6 系列中的套接字有效。This method is valid for sockets in the InterNetwork or InterNetworkV6 families.

已通过调用 Listen(Int32)Socket 置于侦听状态,或异步操作已在进行中。The Socket has been placed in a listening state by calling Listen(Int32), or an asynchronous operation is already in progress.

示例

下面的代码示例启动异步连接尝试。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");
}		

注解

异步BeginConnect完成操作,必须通过调用EndConnect方法。The asynchronous BeginConnect operation must be completed by calling the EndConnect method. 通常情况下,通过调用该方法requestCallback委托。Typically, the method is invoked by the requestCallback delegate.

此方法不会阻止,直到完成该操作。This method does not block until the operation is complete. 若要阻止,直到完成该操作后,使用之一Connect方法重载。To block until the operation is complete, use one of the Connect method overloads.

若要取消挂起调用BeginConnect方法,关闭SocketTo cancel a pending call to the BeginConnect method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginConnect调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginConnect method is called. 随后调用EndConnect方法将引发ObjectDisposedException以指示已取消该操作。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

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

如果以前已断开此套接字,然后BeginConnect必须在操作完成之前不会退出的线程上调用。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. 此外EndPoint,它是使用必须不同。Also the EndPoint that is used must be different.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

另请参阅

适用于