none
TcpClient, 3 attempts of 5 seconds wait until a connection takes place. RRS feed

  • Question

  • Hello,

    I want to wait a maximum of 15 seconds to connect.  (3 attempts)

    The function not wait.
    if (!asyncResultConnection.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5))) //, false))
    What is wrong, how to do it right?
    IP = 127.0.0.1, Port = 99
    Thanks in advance.

    Best regards Markus

    IP = ip;
    Port = port;
    AttemptsCountOfConnect = 0;
    
    while (true)
    {
    	TClient = new TcpClient();
    
    	Trace.WriteLine("[Client] Attempting connection to server " + ip + ":" + port);
    	
    
    	//TClient.Connect(ip, port);  
    
    	IAsyncResult asyncResultConnection = TClient.BeginConnect(IP, Port, null, null);
    	WaitHandle wh = asyncResultConnection.AsyncWaitHandle;
    	try
    	{
    		if (!asyncResultConnection.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5))) //, false))
    		{
    			TClient.Close();
    			//AttemptsCountOfConnect++;
    			//Log.Info($"[Client] AttemptsCountOfConnect: {AttemptsCountOfConnect}");
    
    			//if (AttemptsCountOfConnect > 2)
    			//    throw new Exception($"Maximum attempts are reached to server. {AttemptsCountOfConnect}");
    			//else
    			//    continue;
    		}
    		TClient.EndConnect(asyncResultConnection);
    	}
    	catch (Exception exSocket)
    	{
    		AttemptsCountOfConnect++;
    		Log.Info($"[Client] AttemptsCountOfConnect: {AttemptsCountOfConnect}, {exSocket.StackTrace}");
    
    		if (AttemptsCountOfConnect > 2)
    			throw new Exception($"Maximum attempts are reached to FIS server. {AttemptsCountOfConnect}");
    		else
    			continue;
    	}
    	finally
    	{
    		wh.Close();
    	}

    Monday, February 12, 2018 5:34 PM

All replies

  • Hello Markus,

    The AsyncWaitHandle.WaitOne() method will block the current thread until the current instance receives a signal. For your circumstance of "not wait." I assume that the connection successfully build or return with exception immediately. Did you notice the TClient.BeginConnect 3rd parameter, when the connection complete it will invoke callback function.

    you also could take reference the below timeout method using Task.WhenAny.

      static async Task<string> DownloadStringWithTimeout(string uri)
            {
                using (var client = new HttpClient())
                {
                    var downloadTask = client.GetStringAsync(uri);
    
                    var timeoutTask = Task.Delay(3000);
    
                    var completedTask = await Task.WhenAny(downloadTask, timeoutTask);
    
                    if (completedTask == timeoutTask)
                        return null;
                    return await downloadTask;
                }
            }

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 13, 2018 6:02 AM
    Moderator
  • Hello,
    >Did you notice the TClient.BeginConnect 3rd parameter, when the connection complete
    >it will invoke callback function.
    I saw this, but it is not working.
    I haven't HttpClient() only TcpClient.
    I just want to connect. If no connection is possible, try 3 times.
    I haven't static async Task<string>
    In my class TCPClient is a member of my class.
    Is not possible to make for each request a new connection.
    Is there not an example of how to do this correctly with TCPClient?
        //if (!TClient.ConnectAsync(IP, Port).Wait(1000))
     Works also not.
    With best regards Markus
    Tuesday, February 13, 2018 5:02 PM
  • Hello Markus,

    >>The function not wait.

    The reason is that the connection build "successfully", which contains situation that server refused immediate. This applies to weak network and your code seems right for setting timeout feature.

    https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, February 27, 2018 7:56 AM
    Moderator
  • The reason is that the connection build "successfully", which contains situation that server refused immediate. This applies to weak network and your code seems right for setting timeout feature.

    https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient

    Hello Neil Hu,

    >your code seems right for setting timeout

    ok, but which Version your prefer from stackoverflow?

    Greeting Markus

    Tuesday, February 27, 2018 5:00 PM
  • Hello Markus,

    You could adopt Jon suggestion, it's great idea to use the async BeginConnect method of TcpClient. Job just like as you have done.

    https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.beginconnect(v=vs.110).aspx

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, March 7, 2018 3:06 AM
    Moderator
  • Hello Neil Hu,

    >...just like as you have done.

    OK, but maybe you have it or you know it a complete WPF Project to send, receive Messages.

    Greeting Markus

    Sunday, March 11, 2018 11:43 AM