Export (0) Print
Expand All
10 out of 19 rated this helpful - Rate this topic

TcpClient Class

Provides client connections for TCP network services.

Namespace: System.Net.Sockets
Assembly: System (in system.dll)

public class TcpClient : IDisposable
public class TcpClient implements IDisposable
public class TcpClient implements IDisposable

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.

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();
}

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 = (Int32)13000;
        TcpClient client = new TcpClient(server, (int)port);

        // Translate the passed message into ASCII and store
        // it as a Byte array.
        System.Byte data[] = (System.Byte[])
            System.Text.Encoding.get_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((ubyte[])data, 0, data.length);
        Console.WriteLine("Sent: {0}", message);

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

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

        // Read the first batch of the TcpServer response bytes.
        Int32 bytes = (Int32)stream.Read((ubyte[])data, 0, data.length);
        responseData = System.Text.Encoding.get_ASCII().GetString(
            (ubyte[])data, 0, (int)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();
} //Connect

  • SocketPermission  to establish an outgoing connection or accept an incoming request.
System.Object
  System.Net.Sockets.TcpClient
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

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

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

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 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.