Ebooks

C# TcpClient tutorial

C# TcpClient tutorial shows how to create network programs with TcpClient in C#. C# tutorial is a comprehensive tutorial on C# language.

C# TcpClient

TcpClient class provides simple methods for connecting, sending, and receiving stream data over a network.

C# TcpClient HEAD request

The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method.

Program.cs
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;

namespace HeadRequest
{
    class Program
    {
        static void Main(string[] args)
        {
            using var client = new TcpClient();

            var hostname = "webcode.me";
            client.Connect(hostname, 80);

            using NetworkStream networkStream = client.GetStream();
            networkStream.ReadTimeout = 2000;

            using var writer = new StreamWriter(networkStream);

            var message = "HEAD / HTTP/1.1\r\nHost: webcode.me\r\nUser-Agent: C# program\r\n" 
                + "Connection: close\r\nAccept: text/html\r\n\r\n";

            Console.WriteLine(message);

            using var reader = new StreamReader(networkStream, Encoding.UTF8);

            byte[] bytes = Encoding.UTF8.GetBytes(message);
            networkStream.Write(bytes, 0, bytes.Length);

            Console.WriteLine(reader.ReadToEnd());
        }
    }
}

In the example, we send a HEAD request to webcode.me. The request is synchronous.

using var client = new TcpClient();

A new TcpClient is created. The using keyword releases the resource when the variable goes out of scope.

var hostname = "webcode.me";
client.Connect(hostname, 80);

With the Connect() method, we connect to the site using the specified port.

using NetworkStream networkStream = client.GetStream();
networkStream.ReadTimeout = 2000;

We get a NetworkStream and set a read timeout.

using var writer = new StreamWriter(networkStream);

A StreamWriter is created. It is used to write data to the created network stream.

var message = "HEAD / HTTP/1.1\r\nHost: webcode.me\r\nUser-Agent: C# program\r\n" +
    "Connection: close\r\nAccept: text/html\r\n\r\n";

We define a HEAD request. A HEAD request is issued with the HEAD command followed by the resource URL and HTTP protocol version. Note that the \r\n characters are part of the syntax. The details are described in RFC 7231 document.

using var reader = new StreamReader(networkStream, Encoding.UTF8);

We create a StreamReader for reading the response.

byte[] bytes = Encoding.UTF8.GetBytes(message);
networkStream.Write(bytes, 0, bytes.Length);

The text command is transformed into bytes with the GetBytes() method. The bytes are written to the network stream with the Write() method.

Console.WriteLine(reader.ReadToEnd());

We read the response and write it to the console.

$ dotnet run
HEAD / HTTP/1.1
Host: webcode.me
User-Agent: C# program
Connection: close
Accept: text/html


HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Sat, 23 Nov 2019 12:01:18 GMT
Content-Type: text/html
Content-Length: 348
Last-Modified: Sat, 20 Jul 2019 11:49:25 GMT
Connection: close
ETag: "5d32ffc5-15c"
Accept-Ranges: bytes

This is a sample output.

C# TcpClient GET request

The HTTP GET method requests a representation of the specified resource.

Program.cs
using System;
using System.IO;
using System.Text;
using System.Net.Sockets;

namespace GetRequest
{
    class Program
    {
        static void Main(string[] args)
        {
            using var client = new TcpClient();

            var hostname = "webcode.me";
            client.Connect(hostname, 80);

            using NetworkStream networkStream = client.GetStream();
            networkStream.ReadTimeout = 2000;

            using var writer = new StreamWriter(networkStream);

            var message = @"GET / HTTP/1.1
Accept: text/html, charset=utf-8
Accept-Language: en-US
User-Agent: C# program
Connection: close
Host: webcode.me" + "\r\n\r\n";

            Console.WriteLine(message);

            using var reader = new StreamReader(networkStream, Encoding.UTF8);
            byte[] bytes = Encoding.UTF8.GetBytes(message);

            networkStream.Write(bytes, 0, bytes.Length);
            Console.WriteLine(reader.ReadToEnd());
        }
    }
}

The example retrieves the home page of the specified website.

        var message = @"GET / HTTP/1.1
Accept: text/html, charset=utf-8
Accept-Language: en-US
User-Agent: C# program
Connection: close
Host: webcode.me" + "\r\n\r\n";

We define a GET request.

$ dotnet run
GET / HTTP/1.1
Accept: text/html, charset=utf-8
Accept-Language: en-US
User-Agent: C# program
Connection: close
Host: webcode.me


HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Sat, 23 Nov 2019 12:09:43 GMT
Content-Type: text/html
Content-Length: 348
Last-Modified: Sat, 20 Jul 2019 11:49:25 GMT
Connection: close
ETag: "5d32ffc5-15c"
Access-Control-Allow-Origin: *
Accept-Ranges: bytes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>

    <p>
         Hello there. How are you?
    </p>

</body>
</html>

This is a sample output.

C# TcpClient async request

In the following example, we create an asynchronous request.

Program.cs
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace AsyncClient
{
    class Program
    {
        async static Task Main(string[] args)
        {
            string host = "webcode.me";
            int port = 80;
            int timeout = 5000;

            using var client = new TcpClient();

            await client.ConnectAsync(host, port);

            using var netstream = client.GetStream();
            using var writer = new StreamWriter(netstream);
            using var reader = new StreamReader(netstream);

            writer.AutoFlush = true;
            netstream.ReadTimeout = timeout;

            var message = @"GET / HTTP/1.1
Accept: text/html, charset=utf-8
Accept-Language: en-US
User-Agent: Console app
Connection: close
Host: webcode.me" + "\r\n\r\n";

            await writer.WriteLineAsync(message);

            string response = await reader.ReadToEndAsync();
            Console.WriteLine($"Server: {response}");
        }
    }
}

The example creates an asynchronous GET request to the webcode.me.

await client.ConnectAsync(host, port);

We connect asynchronously to the server. The await operator suspends the evaluation of the ConnectAsync() method until the asynchronous operation completes.

await writer.WriteLineAsync(message);

We use the WriteLineAsync() to write to the network stream asynchronously.

string response = await reader.ReadToEndAsync();

We use the ReadToEndAsync() to read from the network stream asynchronously.

In this tutorial, we have worked with C# TcpClient.

List all C# tutorials.