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 SocketException,否则Connect将引发。If 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 Connect之前专门将false属性设置为。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. 使用方法可确定完成连接的Socket时间。 PollUse the Poll method to determine when the Socket is finished connecting.

如果启用了 IPv6,并且Connect(String, Int32)调用了方法来连接到解析 IPv6 和 ipv4 地址的主机,则在 IPv4 地址之前将首先尝试连接到 ipv6 地址。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 SocketException,否则Connect将引发。If 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 Connect之前专门将false属性设置为。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. 使用方法可确定完成连接的Socket时间。 PollUse 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 SocketException,否则Connect将引发。If 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 Connect之前专门将false属性设置为。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. 使用方法可确定完成连接的Socket时间。 PollUse 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

注解

如果使用面向连接的协议(例如 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 SocketException,否则Connect将引发。If 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将属性设置为falseConnectThe 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. 使用方法可确定完成连接的Socket时间。 PollUse 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

另请参阅

适用于