Click to Rate and Give Feedback
MSDN
MSDN Library
.NET Development
.NET Framework 4
System.Net.Sockets
TcpClient Class
Collapse All/Expand All Collapse All
.NET Framework Class Library
TcpClient Class

Provides client connections for TCP network services.

System..::.Object
  System.Net.Sockets..::.TcpClient

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)
Visual Basic
Public Class TcpClient _
    Implements IDisposable
C#
public class TcpClient : IDisposable
Visual C++
public ref class TcpClient : IDisposable
F#
type TcpClient =  
    class
        interface IDisposable
    end

The TcpClient type exposes the following members.

  NameDescription
Public methodTcpClient()()()Initializes a new instance of the TcpClient class.
Public methodTcpClient(AddressFamily)Initializes a new instance of the TcpClient class with the specified family.
Public methodTcpClient(IPEndPoint)Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.
Public methodTcpClient(String, Int32)Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.
Top
  NameDescription
Protected propertyActiveGets or set a value that indicates whether a connection has been made.
Public propertyAvailableGets the amount of data that has been received from the network and is available to be read.
Public propertyClientGets or sets the underlying Socket.
Public propertyConnectedGets a value indicating whether the underlying Socket for a TcpClient is connected to a remote host.
Public propertyExclusiveAddressUseGets or sets a Boolean value that specifies whether the TcpClient allows only one client to use a port.
Public propertyLingerStateGets or sets information about the linger state of the associated socket.
Public propertyNoDelayGets or sets a value that disables a delay when send or receive buffers are not full.
Public propertyReceiveBufferSizeGets or sets the size of the receive buffer.
Public propertyReceiveTimeoutGets or sets the amount of time a TcpClient will wait to receive data once a read operation is initiated.
Public propertySendBufferSizeGets or sets the size of the send buffer.
Public propertySendTimeoutGets or sets the amount of time a TcpClient will wait for a send operation to complete successfully.
Top
  NameDescription
Public methodBeginConnect(IPAddress, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The remote host is specified by an IPAddress and a port number (Int32).
Public methodBeginConnect(array<IPAddress>[]()[], Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The remote host is specified by an IPAddress array and a port number (Int32).
Public methodBeginConnect(String, Int32, AsyncCallback, Object)Begins an asynchronous request for a remote host connection. The remote host is specified by a host name (String) and a port number (Int32).
Public methodCloseDisposes this TcpClient instance and requests that the underlying TCP connection be closed.
Public methodConnect(IPEndPoint)Connects the client to a remote TCP host using the specified remote network endpoint.
Public methodConnect(IPAddress, Int32)Connects the client to a remote TCP host using the specified IP address and port number.
Public methodConnect(array<IPAddress>[]()[], Int32)Connects the client to a remote TCP host using the specified IP addresses and port number.
Public methodConnect(String, Int32)Connects the client to the specified port on the specified host.
Protected methodDisposeReleases the unmanaged resources used by the TcpClient and optionally releases the managed resources.
Public methodEndConnectAsynchronously accepts an incoming connection attempt.
Public methodEquals(Object)Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected methodFinalizeFrees resources used by the TcpClient class. (Overrides Object..::.Finalize()()().)
Public methodGetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public methodGetStreamReturns the NetworkStream used to send and receive data.
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodToStringReturns a string that represents the current object. (Inherited from Object.)
Top
  NameDescription
Explicit interface implemetationPrivate methodIDisposable..::.DisposeInfrastructure. Releases all resources used by the TcpClient.
Top

The TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network in synchronous blocking mode.

In order for TcpClient to connect and exchange data, a TcpListener or Socket created with the TCP ProtocolType must be listening for incoming connection requests. You can connect to this listener in one of the following two ways:

  • Create a TcpClient and call one of the three available Connect methods.

  • Create a TcpClient using the host name and port number of the remote host. This constructor will automatically attempt a connection.

NoteNote

If you want to send connectionless datagrams in synchronous blocking mode, use the UdpClient class.

Notes to Inheritors

To send and receive data, use the GetStream method to obtain a NetworkStream. Call the Write and Read methods of the NetworkStream to send and receive data with the remote host. Use the Close method to release all resources associated with the TcpClient.

The following code example establishes a TcpClient connection.

Visual Basic
Shared Sub Connect(server As [String], message As [String])
   Try
      ' Create a TcpClient.
      ' Note, for this client to work you need to have a TcpServer 
      ' connected to the same address as specified by the server, port
      ' combination.
      Dim port As Int32 = 13000
      Dim client As New TcpClient(server, port)

      ' Translate the passed message into ASCII and store it as a Byte array.
      Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)

      ' Get a client stream for reading and writing.
      '  Stream stream = client.GetStream();
      Dim stream As NetworkStream = client.GetStream()

      ' Send the message to the connected TcpServer. 
      stream.Write(data, 0, data.Length)

      Console.WriteLine("Sent: {0}", message)

      ' Receive the TcpServer.response.
      ' Buffer to store the response bytes.
      data = New [Byte](256) {}

      ' String to store the response ASCII representation.
      Dim responseData As [String] = [String].Empty

      ' Read the first batch of the TcpServer response bytes.
      Dim bytes As Int32 = stream.Read(data, 0, data.Length)
      responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
      Console.WriteLine("Received: {0}", responseData)

      ' Close everything.
      stream.Close()
      client.Close()
   Catch e As ArgumentNullException
      Console.WriteLine("ArgumentNullException: {0}", e)
   Catch e As SocketException
      Console.WriteLine("SocketException: {0}", e)
   End Try

   Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
   Console.Read()
End Sub 'Connect
C#
static void Connect(String server, String message) 
{
  try 
  {
    // Create a TcpClient.
    // Note, for this client to work you need to have a TcpServer 
    // connected to the same address as specified by the server, port
    // combination.
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);

    // Translate the passed message into ASCII and store it as a Byte array.
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);         

    // Get a client stream for reading and writing.
   //  Stream stream = client.GetStream();

    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length);

    Console.WriteLine("Sent: {0}", message);         

    // Receive the TcpServer.response.

    // Buffer to store the response bytes.
    data = new Byte[256];

    // String to store the response ASCII representation.
    String responseData = String.Empty;

    // Read the first batch of the TcpServer response bytes.
    Int32 bytes = stream.Read(data, 0, data.Length);
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    Console.WriteLine("Received: {0}", responseData);         

    // Close everything.
    stream.Close();         
    client.Close();         
  } 
  catch (ArgumentNullException e) 
  {
    Console.WriteLine("ArgumentNullException: {0}", e);
  } 
  catch (SocketException e) 
  {
    Console.WriteLine("SocketException: {0}", e);
  }

  Console.WriteLine("\n Press Enter to continue...");
  Console.Read();
}
Visual C++
void Connect( String^ server, String^ message )
{
   try
   {
      // Create a TcpClient.
      // Note, for this client to work you need to have a TcpServer 
      // connected to the same address as specified by the server, port
      // combination.
      Int32 port = 13000;
      TcpClient^ client = gcnew TcpClient( server,port );

      // Translate the passed message into ASCII and store it as a Byte array.
      array<Byte>^data = Text::Encoding::ASCII->GetBytes( message );

      // Get a client stream for reading and writing.
      //  Stream stream = client->GetStream();

      NetworkStream^ stream = client->GetStream();

      // Send the message to the connected TcpServer. 
      stream->Write( data, 0, data->Length );

      Console::WriteLine( "Sent: {0}", message );

      // Receive the TcpServer::response.

      // Buffer to store the response bytes.
      data = gcnew array<Byte>(256);

      // String to store the response ASCII representation.
      String^ responseData = String::Empty;

      // Read the first batch of the TcpServer response bytes.
      Int32 bytes = stream->Read( data, 0, data->Length );
      responseData = Text::Encoding::ASCII->GetString( data, 0, bytes );
      Console::WriteLine( "Received: {0}", responseData );

      // Close everything.
      client->Close();
   }
   catch ( ArgumentNullException^ e ) 
   {
      Console::WriteLine( "ArgumentNullException: {0}", e );
   }
   catch ( SocketException^ e ) 
   {
      Console::WriteLine( "SocketException: {0}", e );
   }

   Console::WriteLine( "\n Press Enter to continue..." );
   Console::Read();
}

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
  • SocketPermission 

    Permission to establish an outgoing connection or accept an incoming request.

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
A PowerShell example as an IP and Port Scanner      Jeffrey S. Patton   |   Edit   |   Show History
$Range = 1..25
$Subnet = '10.133.3'
$Ports = 135,139,445,67,68,53,143,993,389,636,110,995,25,119,563,21,20,80,443,531,2053,543,464,88,544
foreach ($Octet in $Range)
{
$IPAddress = "$($Subnet).$($Octet)"
$IP = $null
$Mac = $null
$MacAddress = $null
$PortList = @()
try
{
$IP = Test-Connection -ComputerName $IPAddress -Count 1 -ErrorAction Stop
$Mac = (&;; arp -a $IP.Address)
$MacAddress = ($mac | ? { $_ -match $IP.Address } ) -match "([0-9A-F]{2}([:-][0-9A-F]{2}){5})"
if ($Matches)
{
try
{
$mac = [system.net.networkinformation.physicaladdress]::parse($Matches[0].ToUpper())
}
catch
{
$mac = ''
}
}
foreach ($Port in $Ports)
{
$Socket = New-Object System.Net.Sockets.TcpClient
$Socket.Client.ReceiveTimeout = 1000
$Socket.Client.SendTimeout = 2000
try
{
$Socket.Connect($IP.Address, $port)
$Result = $Socket.Connected
if ($Result -eq $true)
{
$Portlist += $Port
}
}
catch
{
}
$Socket.Close()
}
$Name = [System.Net.Dns]::GetHostEntry($IP.Address).Hostname
New-Object -TypeName PSObject -Property @{
IP = $IP.Address
Name = $Name
MAC = $Mac
PortList = $PortList
}
}
catch
{
$Message = $Error[0].Exception
#Write-Host $Message
$IP = $null
$Mac = $null
$MacAddress = $null
}
}
Tags What's this?: Add a tag
Flag as ContentBug
Can't Close Client and then Connect      Joel Engineer   |   Edit   |   Show History
You can't close a TCP client and then Connect to a different Server. After closing you need to call the client class construtor using new. The class destructor doesn't work on the TCP client, it is not allowed. This may cause a memory leak. Not sure.
Tags What's this?: Add a tag
Flag as ContentBug
ONLY IF CLIENT AND SERVER IN SAME COMPUTER      PSHM19 ... azzdog   |   Edit   |   Show History
I know i must be doing something very stupid... but really im new on this and i tried really some hours... so hope can get some help on mercy :)!! $0$0 $0 $0created this example of Client and Server compiled both and it works fine. IF in SAME computer adress 127.0.0.1 then i tried in 2 diferente computers with diferent internet conections. i searched on my ip website to get ip of server computer and changed the client to conect to that ip. however it doesnt work... i tried also with ipconfig in prompt wich gave me diferent ip adress!!!! but also no result :( it was suposed to work what am i doing wrong???$0 $0$0 $0 $0googling 'what's my ip' only get your external ip (what the internet sees). is your server and host computers BOTH on the same network? if so, then don't google what's my IP. instead, go to command prompt, and type ipconfig (this command gets your current ip configuration settings, which is what your network sees). this is your internal ip (this is what you need!) (make sure you get your IPv4 address, not IPv6 or subnet mask. using IPv6 won't guarantee it will work)$0
Tags What's this?: Add a tag
Flag as ContentBug
Re: ONLY IF CLIENT AND SERVER IN SAME COMPUTER      Screeching Demon ... azzdog   |   Edit   |   Show History
I think I may know the cause of your problem as to why the client/server connection works when run on the same machine, but not on seperate machines. You need to set the source IpEndPoint for both to each host's actual IP address rather than 127.0.0.1, since the default source endpoint is set to the first "logical" source host, which would be localhost. It is impossible for a computer to establish a connection to say, 192.168.1.101, if it's still setting the source to 127.0.0.1; as this would cause the remote computer to reply with a packet destined for 127.0.0.1, which makes the remote host reply only to itself. it wouldn't work if you set the default endpoint to 0.0.0.0:0 (that's not a valid IP address), but I found a piece of code which should help you determine the local IP and set it as the endpoint automatically. Please see http://msdn.microsoft.com/en-us/library/3bsb3c8f.aspx$0 $0 I hope this helps, since I haven't tested it out. Good luck! $0$0 $0 $0127.0.0.1 is the localhost address. its not the address for any particular machine if you want to connect to your own machine, use 127.0.0.1$0
Tags What's this?: Add a tag
Flag as ContentBug
how to loop until connection to server is ready      LebShadow   |   Edit   |   Show History
How to make the system sleeps if there is no TCP connection to the server?
Tags What's this?: Add a tag
Flag as ContentBug
Difficult class      Arne De Herdt ... Thomas Lee   |   Edit   |   Show History
Why is this class so difficult to use for a simple connect &;; reconnect?

i'm the programmer of my software and when i decide to close a connection, I expect the component to simply terminate the socket and not dispose the whole object. Currently I have to go to great lengths to get a simple TcpClient to reconnect to a remote location after a disconnect occurs.

And NO I don't wish to construct a new object the whole time for every connection attempt, I simply wish to reuse my object.

Why am I forced to dispose objects when I simply wish to close?

[tfl - 10 10 10] Hi - and thanks for your post.You should post questions like this to the MSDN Forums at http://forums.microsoft.com/msdn. You are much more likely get a quick response 

using the forums than through the Community Content.

For specific help about:
.Net Development : http://social.msdn.microsoft.com/Forums/en-US/category/visualstudio
Open Specifications : http://social.msdn.microsoft.com/Forums/en-US/category/openspecifications
SharePoint 2010 : http://social.msdn.microsoft.com/Forums/en-US/category/sharepoint2010
SQL : http://social.msdn.microsoft.com/Forums/en-US/category/sqlserver
Visual Studio : http://social.msdn.microsoft.com/Forums/en-US/category/visualstudio

Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker