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. 在极少数情况下, 必须通过Socket state参数将BeginConnect传递给。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传递给方法。 statePass 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. 当你希望原始线程继续ManualResetEvent执行时, 请在回调方法中调用的 Set 方法。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 , 则将SocketException引发。If 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方法调用, 请Socket关闭。To cancel a pending call to the BeginConnect method, close the Socket. 如果在异步操作过程中调用BeginConnect 方法,则会调用向方法提供的回调。CloseWhen 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方法调用, 请Socket关闭。To cancel a pending call to the BeginConnect method, close the Socket. 如果在异步操作过程中调用BeginConnect 方法,则会调用向方法提供的回调。CloseWhen 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方法调用, 请Socket关闭。To cancel a pending call to the BeginConnect method, close the Socket. 如果在异步操作过程中调用BeginConnect 方法,则会调用向方法提供的回调。CloseWhen 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(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方法调用, 请Socket关闭。To cancel a pending call to the BeginConnect method, close the Socket. 如果在异步操作过程中调用BeginConnect 方法,则会调用向方法提供的回调。CloseWhen 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.

另请参阅

适用于