C# Socket BeginConnect give a connection n seconds to connect

Markus Freitag 3,791 Reputation points
2023-02-22T06:04:53.47+00:00

Is there any way in .NET4.7.2 so that I can give a connection 60 seconds to connect.

Unfortunately, this solution will not work. Wait only 2 seconds instead of 60 seconds

The idea is good. Maybe someone sees the error, why this does not work.

//TcpClient needs to persist for life of form...
private TcpClient _client = new TcpClient();


private async void btnAsynConnect_Click(object sender, EventArgs e)
{
	Stopwatch s = new Stopwatch();
	try
	{
		//All this is running on the UI thread                
		if (Ipbox.Text.Length == 0 || !Int32.TryParse(PortBox.Text, out var port))
		{
			MessageBox.Show("Missing data", "Error");
			return;
		};

		//Call the async method on a worker thread
		var cancelAfter = new CancellationTokenSource();

	   
		s.Start(); // Start 

		cancelAfter.CancelAfter(60000);
		await _client.ConnectAsync(Ipbox.Text, port, cancelAfter.Token);
	   

		//The async method is complete and this code is now running on the UI thread again                
		MessageBox.Show("Success", "Connect");
	}
	catch (OperationCanceledException)
	{
		// Algorythmus
		s.Stop();
		TimeSpan timeSpan = s.Elapsed;
		MessageBox.Show(String.Format("Timeout Time: {0}h{1}m{2}s{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds), "Connect Failed");
	}
	catch (Exception ex)
	{
		 // Algorythmus
		s.Stop();
		TimeSpan timeSpan = s.Elapsed;
		MessageBox.Show(ex.Message + Environment.NewLine + String.Format("Timeout Time: {0}h{1}m{2}s{3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds), "Connect Failed");
	};
	
	
	
public static class Extensions
{
	public static async Task ConnectAsync(this TcpClient tcpClient, string host, int port, CancellationToken cancellationToken)
	{
		if (tcpClient == null)
		{
			throw new ArgumentNullException(nameof(tcpClient));
		}

		cancellationToken.ThrowIfCancellationRequested();

		using (cancellationToken.Register(() => tcpClient.Close()))
		{
			try
			{
				cancellationToken.ThrowIfCancellationRequested();

				await tcpClient.ConnectAsync(host, port).ConfigureAwait(false);
			}
			catch (NullReferenceException) when (cancellationToken.IsCancellationRequested)
			{
				cancellationToken.ThrowIfCancellationRequested();
			}
		}
	}
}
Developer technologies | .NET | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2023-02-23T16:05:57.69+00:00

    The error message indicates the server you're trying to connect to using the IP/port is rejecting the call. This doesn't have anything to do with cancellation or your code. You're trying to connect to a machine and port that isn't listening for a connection.

    Confirm that the IP address/port is actively listening, meaning you have a TCP server listening for connections on that port. Given that you're using your local machine you should also confirm that it is listening on port 7775. Note that your firewall may be getting in the way so ensure that the firewall allows the connection through as well. This is generally not a problem for localhost though.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.