This topic has not yet been rated - Rate this topic

Socket::Connect Method (EndPoint)

Establishes a connection to a remote host.

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)
public:
void Connect(
	EndPoint^ remoteEP
)

Parameters

remoteEP
Type: System.Net::EndPoint

An EndPoint that represents the remote device.

ExceptionCondition
ArgumentNullException

remoteEP is nullptr.

SocketException

An error occurred when attempting to access the socket. See the Remarks section for more information.

ObjectDisposedException

The Socket has been closed.

SecurityException

A caller higher in the call stack does not have permission for the requested operation.

InvalidOperationException

The Socket is Listening.

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. If you are using a connectionless protocol, Connect establishes a default remote host. 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.

If you are using a connectionless protocol such as UDP, you do not have to call Connect before sending and receiving data. You can use SendTo and ReceiveFrom to synchronously communicate with a remote host. If you do call Connect, any datagrams that arrive from an address other than the specified default will be discarded. 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. If you receive a SocketException, use the SocketException::ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.

The Connect method will block, unless you specifically set the Blocking property to false prior to calling Connect. 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. You can use SocketException::ErrorCode to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error. If the error returned WSAEWOULDBLOCK, the remote host connection has been initiated by a connection-oriented Socket, but has not yet completed successfully. Use the Poll method to determine when the Socket is finished connecting.

NoteNote:

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. If you want to change the default remote host, call Connect again with the desired endpoint.

NoteNote:

If the socket has been previously disconnected, then you cannot use this method to restore the connection. Use one of the asynchronous BeginConnect methods to reconnect. This is a limitation of the underlying provider.

NoteNote:

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing.

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 );
client.Connect(anEndPoint);
if (!client.Connected) 
{
  Console.WriteLine("Winsock error: "
     + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
} 

 // 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("Connected from an exception!");
   else
   {
     Console.WriteLine("Disconnected: {0}!", e.NativeErrorCode);
   }
 }
 finally
 {
   client.Blocking = blockingState;
 }

 Console.WriteLine("Connected: {0}", client.Connected);
}

[STAThread]
int main()
{
#if FOOZ
  Socket* s = new Socket(AddressFamily::InterNetwork, 
			 SocketType::Stream,
			 ProtocolType::Tcp);

    string host = "localhost";
    int port = 80;

    IPHostEntry hostEntry = Dns::Resolve(host);
    IPEndPoint EPHost = new IPEndPoint(hostEntry->AddressList[0], port);

    ConnectAndCheck(s, EPHost);
#endif
}

#if FOOZ
public class Sample
{
  static void ConnectAndCheck(Socket client, EndPoint anEndPoint)
  {
    client.Connect(anEndPoint);
    if (!client.Connected) 
    {
      Console.WriteLine("Winsock error: "
         + Convert.ToString(System.Runtime.InteropServices.Marshal.GetLastWin32Error()));
    } 

     // 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("Connected from an exception!");
       else
       {
         Console.WriteLine("Disconnected: {0}!", e.NativeErrorCode);
       }
     }
     finally
     {
       client.Blocking = blockingState;
     }

     Console.WriteLine("Connected: {0}", client.Connected);

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.