Export (0) Print
Expand All

Using TCP Services

The TcpClient class requests data from an Internet resource using TCP. The methods and properties of TcpClient abstract the details for creating a Socket for requesting and receiving data using TCP. Because the connection to the remote device is represented as a stream, data can be read and written with .NET Framework stream-handling techniques.

The TCP protocol establishes a connection with a remote endpoint and then uses that connection to send and receive data packets. TCP is responsible for ensuring that data packets are sent to the endpoint and assembled in the correct order when they arrive.

To establish a TCP connection, you must know the address of the network device hosting the service you need and you must know the TCP port that the service uses to communicate. The Internet Assigned Numbers Authority (Iana) defines port numbers for common services (see www.iana.org/assignments/port-numbers). Services not on the Iana list can have port numbers in the range 1,024 to 65,535.

The following example demonstrates setting up a TcpClient to connect to a time server on TCP port 13.

using System;
using System.Net.Sockets;
using System.Text;

public class TcpTimeClient {
    private const int portNum = 13;
    private const string hostName = "host.contoso.com";

    public static int Main(String[] args) {
        try {
            TcpClient client = new TcpClient(hostName, portNum);

            NetworkStream ns = client.GetStream();
            
            byte[] bytes = new byte[1024];
            int bytesRead = ns.Read(bytes, 0, bytes.Length);

            Console.WriteLine(Encoding.ASCII.GetString(bytes,0,bytesRead));

            client.Close();

        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        return 0;
    }
}

TcpListener is used to monitor a TCP port for incoming requests and then create either a Socket or a TcpClient that manages the connection to the client. The Start method enables listening, and the Stop method disables listening on the port. The AcceptTcpClient method accepts incoming connection requests and creates a TcpClient to handle the request, and the AcceptSocket method accepts incoming connection requests and creates a Socket to handle the request.

The following example demonstrates creating a network time server using a TcpListener to monitor TCP port 13. When an incoming connection request is accepted, the time server responds with the current date and time from the host server.

using System;
using System.Net.Sockets;
using System.Text;

public class TcpTimeServer {

    private const int portNum = 13;

    public static int Main(String[] args) {
        bool done = false;
        
        TcpListener listener = new TcpListener(portNum);

        listener.Start();

        while (!done) {
            Console.Write("Waiting for connection...");
            TcpClient client = listener.AcceptTcpClient();
            
            Console.WriteLine("Connection accepted.");
            NetworkStream ns = client.GetStream();

            byte[] byteTime = Encoding.ASCII.GetBytes(DateTime.Now.ToString());

            try {
                ns.Write(byteTime, 0, byteTime.Length);
                ns.Close();
                client.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }

        listener.Stop();

        return 0;
    }
    
}
Show:
© 2015 Microsoft