Socket.Connect Socket.Connect Socket.Connect Socket.Connect Method

定义

与远程主机建立连接。Establishes a connection to a remote host.

重载

Connect(String, Int32) Connect(String, Int32) Connect(String, Int32) Connect(String, Int32)

与远程主机建立连接。Establishes a connection to a remote host. 主机由主机名和端口号指定。The host is specified by a host name and a port number.

Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32)

与远程主机建立连接。Establishes a connection to a remote host. 主机由 IP 地址数组和端口号指定。The host is specified by an array of IP addresses and a port number.

Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32)

与远程主机建立连接。Establishes a connection to a remote host. 主机由 IP 地址和端口号指定。The host is specified by an IP address and a port number.

Connect(EndPoint) Connect(EndPoint) Connect(EndPoint) Connect(EndPoint)

与远程主机建立连接。Establishes a connection to a remote host.

Connect(String, Int32) Connect(String, Int32) Connect(String, Int32) Connect(String, Int32)

与远程主机建立连接。Establishes a connection to a remote host. 主机由主机名和端口号指定。The host is specified by a host name and a port number.

public:
 void Connect(System::String ^ host, int port);
public void Connect (string host, int port);
member this.Connect : string * int -> unit
Public Sub Connect (host As String, port As Integer)

参数

host
String String String String

远程主机的名称。The name of the remote host.

port
Int32 Int32 Int32 Int32

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

异常

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

此方法对 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).

示例

下面的代码示例连接到远程终结点,并接着验证连接。The following code example connects to a remote endpoint and then verifies the connection.

// Synchronous connect using host name (resolved by the 
// Connect call.)
static void Connect3( String^ host, int port )
{
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->Connect( host, port );
   Console::WriteLine( "Connection established" );
}

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

    Console.WriteLine("Establishing Connection to {0}", 
        host);
    s.Connect(host, port);
    Console.WriteLine("Connection established");
}		

注解

如果使用面向连接的协议 TCP,如Connect方法以同步方式建立网络连接之间LocalEndPoint和指定的远程主机。If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote host. 如果您使用的是无连接协议,Connect建立默认远程主机。If you are using a connectionless protocol, Connect establishes a default remote host. 调用后Connect可以将数据发送到远程设备与Send方法,或从使用的远程设备接收数据Receive方法。After you call Connect you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

如果使用如 UDP 是无连接协议,不需要调用Connect之前发送和接收数据。If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. 可以使用SendToReceiveFrom能够与远程主机同步通信。You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. 如果调用Connect将丢弃来自指定的默认值以外的地址的任何数据报。If you do call Connect any datagrams that arrive from an address other than the specified default will be discarded. 如果你想要将默认远程主机到广播地址,必须先调用SetSocketOption方法,设置套接字选项设置为SocketOptionName.Broadcast,或Connect将引发SocketExceptionIf you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. 如果你收到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.

Connect 方法将阻止,除非专门设置了Blocking属性设置为false之前调用ConnectConnect method will block, unless you specifically set the Blocking property to false prior to calling Connect. 如果要使用面向连接的协议 TCP,并且确实禁用阻塞等Connect将引发SocketException因为它需要时间来建立连接。If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. 无连接协议将引发异常,因为它们只需建立默认远程主机。Connectionless protocols will not throw an exception because they simply establish a default remote host. 可以使用SocketException.ErrorCode若要获取特定的错误代码。You can use SocketException.ErrorCode 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. 如果 WSAEWOULDBLOCK 返回的错误,已通过面向连接的发起远程主机连接Socket,但未尚未成功完成。If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. 使用Poll方法来确定何时Socket完成连接。Use the Poll method to determine when the Socket is finished connecting.

如果启用了 IPv6 和Connect(String, Int32)调用方法来连接到的主机,解析为 IPv6 和 IPv4 地址、 IPv6 地址将与连接尝试之前的 IPv4 地址的第一个。If IPv6 is enabled and the Connect(String, Int32) method is called to connect to a host that resolves to both IPv6 and IPv4 addresses, the connection to the IPv6 address will be attempted first before the IPv4 address. 这可能会延迟的时间来建立连接,如果主机未侦听 IPv6 地址。This may have the effect of delaying the time to establish the connection if the host is not listening on the IPv6 address.

备注

如果使用的是面向连接的协议和未调用Bind之前调用Connect,基础服务提供程序将分配的本地网络地址和端口号。If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the 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 complete a send or receive operation. 如果你想要更改默认远程主机,则调用Connect再次使用所需终结点。If you want to change the default remote host, call Connect again with the desired endpoint.

备注

如果之前断开连接的套接字,则不能使用此方法以还原连接。If the socket has been previously disconnected, then you cannot use this method to restore the connection. 使用异步之一BeginConnect方法来重新连接。Use one of the asynchronous BeginConnect methods to reconnect. 这是基础提供程序的限制。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.

Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32) Connect(IPAddress[], Int32)

与远程主机建立连接。Establishes a connection to a remote host. 主机由 IP 地址数组和端口号指定。The host is specified by an array of IP addresses and a port number.

public:
 void Connect(cli::array <System::Net::IPAddress ^> ^ addresses, int port);
public void Connect (System.Net.IPAddress[] addresses, int port);
member this.Connect : System.Net.IPAddress[] * int -> unit
Public Sub Connect (addresses As IPAddress(), port As Integer)

参数

addresses
IPAddress[]

远程主机的 IP 地址。The IP addresses of the remote host.

port
Int32 Int32 Int32 Int32

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

异常

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

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

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

已通过调用 Listen(Int32)Socket 置于侦听状态。The Socket has been placed in a listening state by calling Listen(Int32).

示例

下面的代码示例连接到远程终结点,并接着验证连接。The following code example connects to a remote endpoint and then verifies the connection.

// Synchronous connect using Dns.ResolveToAddresses to 
// resolve the host name.
static void Connect2( String^ host, int port )
{
   array<IPAddress^>^IPs = Dns::GetHostAddresses( host );
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->Connect( IPs, port );
   Console::WriteLine( "Connection established" );
}


// Synchronous connect using Dns.GetHostAddresses to 
// resolve the host name.
public static void Connect2(string host, int port)
{
    IPAddress[] IPs = Dns.GetHostAddresses(host);

    Socket s = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream,
        ProtocolType.Tcp);
    Console.WriteLine("Establishing Connection to {0}", 
        host);
    s.Connect(IPs, port);
    Console.WriteLine("Connection established");
}		

注解

此方法通常用于调用后立即GetHostAddresses,这可以为单个主机返回多个 IP 地址。This method is typically used immediately after a call to GetHostAddresses, which can return multiple IP addresses for a single host. 如果使用面向连接的协议 TCP,如Connect方法以同步方式建立网络连接之间LocalEndPoint和指定的远程终结点。If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote endpoint. 如果您使用的是无连接协议,Connect建立默认远程主机。If you are using a connectionless protocol, Connect establishes a default remote host. 调用后Connect可以将数据发送到远程设备与Send方法,或从使用的远程设备接收数据Receive方法。After you call Connect you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

如果使用如 UDP 是无连接协议,不需要调用Connect之前发送和接收数据。If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. 可以使用SendToReceiveFrom能够与远程主机同步通信。You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. 如果调用Connect将丢弃来自指定的默认值以外的地址的任何数据报。If you do call Connect any datagrams that arrive from an address other than the specified default will be discarded. 如果你想要将默认远程主机到广播地址,必须先调用SetSocketOption方法,设置套接字选项设置为SocketOptionName.Broadcast,或Connect将引发SocketExceptionIf you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. 如果你收到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.

Connect 方法将阻止,除非专门设置了Blocking属性设置为false之前调用ConnectConnect method will block, unless you specifically set the Blocking property to false prior to calling Connect. 如果要使用面向连接的协议 TCP,并且确实禁用阻塞等Connect将引发SocketException因为它需要时间来建立连接。If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. 无连接协议将引发异常,因为它们只需建立默认远程主机。Connectionless protocols will not throw an exception because they simply establish a default remote host. 可以使用SocketException.ErrorCode若要获取特定的错误代码。You can use SocketException.ErrorCode 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. 如果 WSAEWOULDBLOCK 返回的错误,已通过面向连接的发起远程主机连接Socket,但未尚未成功完成。If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. 使用Poll方法来确定何时Socket完成连接。Use the Poll method to determine when the Socket is finished connecting.

备注

如果使用的是面向连接的协议和未调用Bind之前调用Connect,基础服务提供程序将分配的本地网络地址和端口号。If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the 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 complete a send or receive operation. 如果你想要更改默认远程主机,则调用Connect再次使用所需终结点。If you want to change the default remote host, call Connect again with the desired endpoint.

备注

如果之前断开连接的套接字,则不能使用此方法以还原连接。If the socket has been previously disconnected, then you cannot use this method to restore the connection. 使用异步之一BeginConnect方法来重新连接。Use one of the asynchronous BeginConnect methods to reconnect. 这是基础提供程序的限制。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.

Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32)

与远程主机建立连接。Establishes a connection to a remote host. 主机由 IP 地址和端口号指定。The host is specified by an IP address and a port number.

public:
 void Connect(System::Net::IPAddress ^ address, int port);
public void Connect (System.Net.IPAddress address, int port);
member this.Connect : System.Net.IPAddress * int -> unit
Public Sub Connect (address As IPAddress, port As Integer)

参数

address
IPAddress IPAddress IPAddress IPAddress

远程主机的 IP 地址。The IP address of the remote host.

port
Int32 Int32 Int32 Int32

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

异常

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

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

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

已通过调用 Listen(Int32)Socket 置于侦听状态。The Socket has been placed in a listening state by calling Listen(Int32).

示例

下面的代码示例连接到远程终结点,并接着验证连接。The following code example connects to a remote endpoint and then verifies the connection.

// Synchronous connect using IPAddress to resolve the 
// host name.
static void Connect1( String^ host, int port )
{
   array<IPAddress^>^IPs = Dns::GetHostAddresses( host );
   Socket^ s = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   Console::WriteLine( "Establishing Connection to {0}", host );
   s->Connect( IPs[ 0 ], port );
   Console::WriteLine( "Connection established" );
}


// Synchronous connect using IPAddress to resolve the 
// host name.
public static void Connect1(string host, int port)
{
    IPAddress[] IPs = Dns.GetHostAddresses(host);

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

    Console.WriteLine("Establishing Connection to {0}", 
        host);
    s.Connect(IPs[0], port);
    Console.WriteLine("Connection established");
}		

注解

如果使用面向连接的协议 TCP,如Connect方法以同步方式建立网络连接之间LocalEndPoint和指定的远程终结点。If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote endpoint. 如果您使用的是无连接协议,Connect建立默认远程主机。If you are using a connectionless protocol, Connect establishes a default remote host. 调用后Connect可以将数据发送到远程设备与Send方法,或从使用的远程设备接收数据Receive方法。After you call Connect you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

如果使用如 UDP 是无连接协议,不需要调用Connect之前发送和接收数据。If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. 可以使用SendToReceiveFrom能够与远程主机同步通信。You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. 如果调用Connect将丢弃来自指定的默认值以外的地址的任何数据报。If you do call Connect any datagrams that arrive from an address other than the specified default will be discarded. 如果你想要将默认远程主机到广播地址,必须先调用SetSocketOption方法,设置套接字选项设置为SocketOptionName.Broadcast,或Connect将引发SocketExceptionIf you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. 如果你收到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.

Connect 方法将阻止,除非专门设置了Blocking属性设置为false之前调用ConnectConnect method will block, unless you specifically set the Blocking property to false prior to calling Connect. 如果要使用面向连接的协议 TCP,并且确实禁用阻塞等Connect将引发SocketException因为它需要时间来建立连接。If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. 无连接协议将引发异常,因为它们只需建立默认远程主机。Connectionless protocols will not throw an exception because they simply establish a default remote host. 可以使用SocketException.ErrorCode若要获取特定的错误代码。You can use SocketException.ErrorCode 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. 如果 WSAEWOULDBLOCK 返回的错误,已通过面向连接的发起远程主机连接Socket,但未尚未成功完成。If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. 使用Poll方法来确定何时Socket完成连接。Use the Poll method to determine when the Socket is finished connecting.

备注

如果使用的是面向连接的协议和未调用Bind之前调用Connect,基础服务提供程序将分配的本地网络地址和端口号。If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the 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 complete a send or receive operation. 如果你想要更改默认远程主机,则调用Connect再次使用所需终结点。If you want to change the default remote host, call Connect again with the desired endpoint.

备注

如果之前断开连接的套接字,则不能使用此方法以还原连接。If the socket has been previously disconnected, then you cannot use this method to restore the connection. 使用异步之一BeginConnect方法来重新连接。Use one of the asynchronous BeginConnect methods to reconnect. 这是基础提供程序的限制。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.

Connect(EndPoint) Connect(EndPoint) Connect(EndPoint) Connect(EndPoint)

与远程主机建立连接。Establishes a connection to a remote host.

public:
 void Connect(System::Net::EndPoint ^ remoteEP);
public void Connect (System.Net.EndPoint remoteEP);
member this.Connect : System.Net.EndPoint -> unit
Public Sub Connect (remoteEP As EndPoint)

参数

remoteEP
EndPoint EndPoint EndPoint EndPoint

表示远程设备的 EndPointAn EndPoint that represents the remote device.

异常

尝试访问套接字时出错。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).

示例

下面的代码示例连接到远程终结点,并接着验证连接。The following code example connects to a remote endpoint and then verifies the connection.

client->Connect( anEndPoint );
if (  !client->Connected )
{
   Console::WriteLine( "Winsock error: {0}", Convert::ToString(
      System::Runtime::InteropServices::Marshal::GetLastWin32Error() ) );
}
   
// This is how you can determine whether a socket is still connected.
bool blockingState = client->Blocking;
try
{
   array<Byte>^tmp = gcnew array<Byte>(1);
   client->Blocking = false;
   client->Send( tmp, 0, static_cast<SocketFlags>(0) );
   Console::WriteLine( L"Connected!" );
}
catch ( SocketException^ e ) 
{
   // 10035 == WSAEWOULDBLOCK
   if ( e->NativeErrorCode.Equals( 10035 ) )
   {
      Console::WriteLine( "Connected from an exception!" );
   }
   else
   {
      Console::WriteLine( "Disconnected: {0}!", e->NativeErrorCode );
   }
}
finally
{
   client->Blocking = blockingState;
}

Console::WriteLine( "Connected: {0}", client->Connected );
// .Connect throws an exception if unsuccessful
client.Connect(anEndPoint);

// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp, 0, 0);
    Console.WriteLine("Connected!");
}
catch (SocketException e) 
{
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorCode.Equals(10035))
    {
        Console.WriteLine("Still Connected, but the Send would block");
    }
    else
    {
        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
    }
}
finally
{
    client.Blocking = blockingState;
}

Console.WriteLine("Connected: {0}", client.Connected);
    ' .Connect throws an exception if unsuccessful
    client.Connect(anEndPoint)
    
    ' This is how you can determine whether a socket is still connected.
    Dim blockingState As Boolean = client.Blocking
    Try
        Dim tmp(0) As Byte
        
        client.Blocking = False
        client.Send(tmp, 0, 0)
        Console.WriteLine("Connected!")
    Catch e As SocketException
        ' 10035 == WSAEWOULDBLOCK
        If e.NativeErrorCode.Equals(10035) Then
            Console.WriteLine("Still Connected, but the Send would block")
        Else
            Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode)
        End If
    Finally
        client.Blocking = blockingState
    End Try
    
    Console.WriteLine("Connected: {0}", client.Connected)

End Sub 'ConnectAndCheck

注解

如果使用面向连接的协议 TCP,如Connect方法以同步方式建立网络连接之间LocalEndPoint和指定的远程终结点。If you are using a connection-oriented protocol such as TCP, the Connect method synchronously establishes a network connection between LocalEndPoint and the specified remote endpoint. 如果您使用的是无连接协议,Connect建立默认远程主机。If you are using a connectionless protocol, Connect establishes a default remote host. 调用后Connect,可以将数据发送到远程设备与Send方法,或从使用的远程设备接收数据Receive方法。After you call Connect, you can send data to the remote device with the Send method, or receive data from the remote device with the Receive method.

如果使用如 UDP 是无连接协议,不需要调用Connect之前发送和接收数据。If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. 可以使用SendToReceiveFrom能够与远程主机同步通信。You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. 如果调用Connect,将丢弃来自指定的默认值以外的地址的任何数据报。If you do call Connect, any datagrams that arrive from an address other than the specified default will be discarded. 如果你想要将默认远程主机到广播地址,必须先调用SetSocketOption方法,设置套接字选项设置为SocketOptionName.Broadcast,或Connect将引发SocketExceptionIf you want to set your default remote host to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast, or Connect will throw a SocketException. 如果你收到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.

Connect方法将阻止,除非专门设置了相应Blocking属性设置为false之前调用ConnectThe Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. 如果要使用面向连接的协议 TCP,并且确实禁用阻塞等Connect将引发SocketException因为它需要时间来建立连接。If you are using a connection-oriented protocol like TCP and you do disable blocking, Connect will throw a SocketException because it needs time to make the connection. 无连接协议将引发异常,因为它们只需建立默认远程主机。Connectionless protocols will not throw an exception because they simply establish a default remote host. 可以使用SocketException.ErrorCode若要获取特定的错误代码。You can use SocketException.ErrorCode 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. 如果 WSAEWOULDBLOCK 返回的错误,已通过面向连接的发起远程主机连接Socket,但未尚未成功完成。If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. 使用Poll方法来确定何时Socket完成连接。Use the Poll method to determine when the Socket is finished connecting.

备注

如果使用的是面向连接的协议和未调用Bind之前调用Connect,基础服务提供程序将分配的本地网络地址和端口号。If you are using a connection-oriented protocol and did not call Bind before calling Connect, the underlying service provider will assign the 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 complete a send or receive operation. 如果你想要更改默认远程主机,则调用Connect再次使用所需终结点。If you want to change the default remote host, call Connect again with the desired endpoint.

备注

如果之前断开连接的套接字,则不能使用此方法以还原连接。If the socket has been previously disconnected, then you cannot use this method to restore the connection. 使用异步之一BeginConnect方法来重新连接。Use one of the asynchronous BeginConnect methods to reconnect. 这是基础提供程序的限制。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.

安全性

SocketPermission
用于连接到远程主机。for connecting to the remote host. 关联的枚举: ConnectAssociated enumeration: Connect

另请参阅

适用于