TcpClient.ConnectAsync Method

Overview

Asynchronously connects the current TcpClient to a remote TCP host and port.

This method is used to initiate a connection to a remote device asynchronously. It returns a task that completes when the connection has been established or when an error has occurred.

Syntax

public virtual System.Threading.Tasks.Task ConnectAsync (string host, int port);
public virtual System.Threading.Tasks.Task ConnectAsync (System.Net.EndPoint remoteEP);

Parameters

Return Value

System.Threading.Tasks.Task

A Task object that represents the asynchronous operation. The Task will complete when the connection is established or when an error occurs.

Exceptions

Remarks

The ConnectAsync method allows you to connect to a remote device without blocking the calling thread. This is particularly useful in UI applications to prevent the interface from becoming unresponsive during network operations.

If the connection attempt times out, a SocketException will be thrown.

Note: For more granular control over connection timeouts, consider using ConnectAsync in conjunction with CancellationToken or managing timeouts manually.

When using the overload that accepts a string host and int port, the .NET runtime will attempt to resolve the host name to an IP address.

Important: Ensure that the remote host is reachable and that a listener is active on the specified port before calling this method.

Examples

C# Example

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

public class TcpClientExample
{
    public static async Task ConnectAndSendAsync(string hostname, int port)
    {
        using (TcpClient client = new TcpClient())
        {
            try
            {
                Console.WriteLine($"Attempting to connect to {hostname}:{port}...");
                await client.ConnectAsync(hostname, port);
                Console.WriteLine("Successfully connected!");

                // Get the network stream for sending and receiving data
                using (NetworkStream stream = client.GetStream())
                {
                    // Example: Send a message
                    string messageToSend = "Hello from TcpClient!";
                    byte[] data = Encoding.ASCII.GetBytes(messageToSend);
                    await stream.WriteAsync(data, 0, data.Length);
                    Console.WriteLine($"Sent: {messageToSend}");

                    // Example: Receive a response (optional)
                    byte[] buffer = new byte[1024];
                    int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    Console.WriteLine($"Received: {response}");
                }
            }
            catch (SocketException ex)
            {
                Console.WriteLine($"Socket Error: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"General Error: {ex.Message}");
            }
            finally
            {
                if (client.Connected)
                {
                    client.Close();
                    Console.WriteLine("Connection closed.");
                }
            }
        }
    }

    public static async Task Main(string[] args)
    {
        // Replace with a valid hostname and port where a TCP listener is running
        string serverHostname = "localhost";
        int serverPort = 13000;

        await ConnectAndSendAsync(serverHostname, serverPort);
    }
}